实体框架:导航属性问题 [英] Entity Framework: Navigation Properties Issue
问题描述
我正与实体框架code-第一,我有一个类课程
其中有一个导航属性学生
:
I am working with Entity Framework code-first, and I have a class Course
which has a navigation property Students
:
public virtual Collection<Student> Students { get; set;}
它的工作不错,但我访问该导航属性,所有的数据从数据库中检索:
It works ok, but as I access this navigation property, all the data is retrieved from the database:
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()
,因为我不想把所有的<$ C $要执行的查询C>学生从数据库中,只有活跃的。
As you can imagine, I need the query to be executed when I do the .ToList()
because I don't want to bring all the Students
from the database, only the active ones.
你知道我在做什么错了?
Do you know what I am doing wrong?
推荐答案
延迟加载加载整个集到内存中。如果你不希望出现这种情况,通过删除虚拟
关键字切换延迟加载关闭和使用查询对象的 DbEntry
:
Lazy loading loads the entire set into memory. If you don't want that, switch lazy loading off by removing the virtual
keyword and use the Query object on the 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
}
时的活动标志,您要实现软删除的指标?如果是的话,这里有一个解决方案:软实体框架删除
您可以投票筛选,包括在这里:允许过滤功能包括扩展方法
You can vote for filtered includes here: Allow filtering for Include extension method
另一种方式做到这一点是与继承。你可以有一个 ActiveStudent
从学生
和 ActiveStudents
继承导航属性以及在课程
类的<code> AllStudents 导航属性。
Another way to do it would be with inheritance. You could have an ActiveStudent
inheriting from Student
and an ActiveStudents
navigation property as well as an AllStudents
navigation property in the Course
class
public virtual Collection<Student> AllStudents { get; set;}
public virtual Collection<ActiveStudent> ActiveStudents { get; set;}
参考:
这篇关于实体框架:导航属性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!