实体框架:导航属性问题 [英] Entity Framework: Navigation Properties Issue

查看:97
本文介绍了实体框架:导航属性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架代码,我有一个类课程,其中有一个导航属性学生

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(),因为我不想从数据库中携带所有的学生,只有活动的。

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?

推荐答案

懒惰加载整个集进入记忆如果您不想要,请通过删除 virtual 关键字来切换延迟加载,并使用 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
}

是活动标志你试图实现软删除的一个指标?如果是这样,在这里有一个解决方案:实体框架中的软删除

Is the "Active" flag an indicator that you are trying to implement soft delete? If so there is a solution here: Soft Delete in Entity Framework

您可以投票选择过滤的包括:允许过滤包含扩展方法

You can vote for filtered includes here: Allow filtering for Include extension method

另一种做法就是继承。您可以从 Student ActiveStudents 继承 ActiveStudent 导航属性以及课程中的 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;}

参考:

a href =http://msdn.microsoft.com/en-US/data/jj574232 =nofollow noreferrer>显式加载相关实体时应用过滤器:

Applying filters when explicitly loading related entities:

这篇关于实体框架:导航属性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆