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

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

问题描述

我正与实体框架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屋!

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