【发布时间】:2015-01-20 22:55:37
【问题描述】:
我正在尝试首先使用 VS 2013 学习 Entity Framework 6 代码。
我正在做与这个问题完全相同的事情:How to eagerly load a many to many relationship with the entity framework code first?
使用相同的设置
public class Student
{
public int Id {get;set}
public string FullName {get;set;}
public virtual ICollection<Course> Courses {get;set;}
}
public class Course
{
public int Id {get;set;}
public string FullName {get;set;}
public virtual ICollection<Student> Students {get;set;}
}
答案
var allStudents = context.Students.Include( s => s.Courses);
但是在调试时我得到一个递归结果。 每个学生都包含一个课程列表,这些课程包含一个学生列表,其中包含课程,包含学生等等....
不使用.Include(...方法也一样
var allStudents = context.Students;
我在一个脚手架 MVC 5 ApiController 中使用它,它抛出:
System.Runtime.Serialization.SerializationException
从模型中删除 Virtual 并仍然使用 .Include(... 抛出:
“SchoolEF.Models.Course”类型的对象图包含循环 如果禁用引用跟踪,则无法序列化。
我想我还没有完全理解如何进行预加载以及如何使用 .Include() 方法。
【问题讨论】:
标签: c# entity-framework ef-code-first eager-loading