【问题标题】:Retrieve tree structured json in ASP.NET Web Api for master-detail entities在 ASP.NET Web Api 中检索主从实体的树结构 json
【发布时间】:2015-05-13 21:23:54
【问题描述】:

我是使用 Asp.Net MVC 5 Web Api2 的新手,我正在开发一个非常小的示例,其中我遇到了一个奇怪的问题。我有两个非常简单的实体类,“学生”和“课程”,它们中的每一个都有一个对另一个的“虚拟 ICollection”引用(使它们的关系多对多)。下面的代码显示了 Student 实体和 Course 实体非常相似,都是指学生类。

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int AdmissionYear { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

我也有这个小的 Api Controller:

public class StudentController : ApiController
{
    private EFStudentRepository rep = new EFStudentRepository();

    public IEnumerable<Student> Get()
    {
        return rep.Students;
    }

    public Student Get(int id)
    {
        Student s = rep.Students.First(x => x.Id == id);
        if (s == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return s;
    }
}

问题是,当我运行应用程序并调用此控制器时,json 输出会显示学生的数据,但不会显示与该学生关联的课程,如下所示:

{"ID":1, "Name":"Mikel", "AdmissionYear":2010, "Courses":null}

事实上,在数据库中,“StudentCourse”表已经自动创建,我还用适当的数据填充了它。特别奇怪的是,当我编写一个呈现 HTML 的普通控制器时,所有数据都正确显示,但在 Api 控制器的情况下却没有。所以基本上它确实显示了主记录的数据,而不是详细记录的数据。

提前致谢。

【问题讨论】:

    标签: json entity-framework asp.net-mvc-5 asp.net-web-api2 master-detail


    【解决方案1】:

    您需要在查询中“包含”导航属性...

    Student s = rep.Students.Include("Courses").First(x => x.Id == id);
    

    【讨论】:

    • 谢谢,但就我而言,没有可以在其中使用的“包含”方法。你确定吗?
    • 我假设 Student 是一个 DbSet,而 EFStudentRepository 是一个 DbContext,因此您正在运行 Linq to Entities 查询。
    • EFStudentRepository 是一个类,我在其中实例化了一个 EFDbContext,它以 IEnumerable 形式返回 Student。
    • 在这种情况下,我将添加一个方法,该方法采用您想要的学生的标识符,然后在该方法中恢复特定学生以及获取相关课程所需的包含。然后将其从方法返回给调用者。
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多