Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ASP.NET Web Api中检索主细节实体的树结构json_Json_Entity Framework_Asp.net Mvc 5_Asp.net Web Api2_Master Detail - Fatal编程技术网

在ASP.NET Web Api中检索主细节实体的树结构json

在ASP.NET Web Api中检索主细节实体的树结构json,json,entity-framework,asp.net-mvc-5,asp.net-web-api2,master-detail,Json,Entity Framework,Asp.net Mvc 5,Asp.net Web Api2,Master Detail,我不熟悉使用Asp.NETMVC5WebAPI2,我正在开发一个非常小的示例,其中我遇到了一个奇怪的问题。我有两个非常简单的实体类,“学生”和“课程”,其中每一个都有一个对另一个的“虚拟ICollection”引用(使它们的关系成为多对多)。下面的代码显示学生实体和课程实体非常相似,它指的是学生类 public class Student { public int Id { get; set; } public string Name { get; set; } publ

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

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; }
}
事实上,在数据库中,“StudentCourse”表是自动创建的,我也用适当的数据填充了它。尤其奇怪的是,当我编写一个呈现HTML的普通控制器时,所有数据都会正确地显示出来,但在Api控制器中却没有。所以基本上它确实显示了主记录的数据,而不是详细记录的数据


提前感谢。

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

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

谢谢,但就我所尝试的而言,这里没有“包含”方法可以使用。你确定吗?我假设Student是一个DbSet,EFStudentRepository是一个DbContext,因此你正在运行一个Linq to Entities查询。EFStudentRepository是一个类,我在其中实例化了一个EFDbContext,它返回Students作为IEnumerable。在这种情况下,我将添加一个方法,该方法使用你想要的Student的标识符然后在该方法中,它恢复特定学生以及获取相关课程所需的包含。然后将其从方法返回给调用方。
{"ID":1, "Name":"Mikel", "AdmissionYear":2010, "Courses":null}
Student s = rep.Students.Include("Courses").First(x => x.Id == id);