【发布时间】: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