实体框架:导航属性问题

asc*_*man 6 .net entity-framework ef-code-first dbcontext

我正在使用Entity Framework代码优先,我有一个Course具有导航属性的类Students:

public virtual Collection<Student> Students { get; set;}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是当我访问此导航属性时,将从数据库中检索所有数据:

var allStudents = course.Students; // Here it retrieves the data
var activeStudents = allStudents.Where(n => n.Active); // Here it filter the data on memory
var listOfActiveStudents = activeStudents.ToList(); // It already has the data on memory.
Run Code Online (Sandbox Code Playgroud)

您可以想象,我需要在执行此操作时执行查询,.ToList()因为我不想Students从数据库中获取所有数据,只有活动数据库.

你知道我做错了什么吗?

Col*_*lin 3

延迟加载将整个集合加载到内存中。如果您不想这样做,请通过删除virtual关键字来关闭延迟加载,并在以下位置使用查询对象DbEntry

public GetCourseWithActiveStudentsLoaded(int courseid)
{
   var course= context.Courses.Find(courseid); 

   context.Entry(course)
          .Collection(c => c.Students)
          .Query()
          .Where(s => s.Active)
          .Load();

   return user
}
Run Code Online (Sandbox Code Playgroud)

“Active”标志是否表明您正在尝试实施软删除?如果是这样,这里有一个解决方案:Soft Delete in Entity Framework

您可以在此处为过滤的包含投票:允许过滤包含扩展方法

另一种方法是继承。您可以在类中拥有ActiveStudent继承StudentActiveStudents导航属性以及导航属性AllStudentsCourse

public virtual Collection<Student> AllStudents { get; set;}
public virtual Collection<ActiveStudent> ActiveStudents { get; set;}
Run Code Online (Sandbox Code Playgroud)

参考:

显式加载相关实体时应用过滤器