我正在使用Entity Framework的Code-First功能,我有一个名为Course
的类,其中包含一个导航属性Students
:
public virtual Collection<Student> Students { get; set;}
它能正常工作,但是当我访问这个导航属性时,所有的数据都会从数据库中检索出来:
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.
正如您所想象的那样,我需要在执行.ToList()
时执行查询,因为我不想将所有Students
从数据库中提取出来,只需要活动的。
您知道我做错了什么吗?
IQueryable
来实现这个。你应该使用外键关系对学生表发出查询。类似于db.Students.Where( s => s.Active && s.UserId == user.UserId )
这样的语句。这将给你一个IQueryable
,能够利用你所寻找的延迟执行。 - Travis Jdb.Entry(user).Collection(u => u.Students).Query().Where(s => s.Active).ToList();
。 这将只加载用户的活动学生。.Collection
返回DbCollectionEntry
,而Query
返回IQueryable
,它们都不会将集合加载到内存中。 在此处使用Where
也将返回IQueryable
,而最终调用ToList
是将集合加载到内存中的地方。 - Travis J