在实体框架中加载具有过滤条件的子对象记录
Posted
技术标签:
【中文标题】在实体框架中加载具有过滤条件的子对象记录【英文标题】:Load child object records with filter condition in Entity Framework 【发布时间】:2013-08-10 17:04:08 【问题描述】:使用实体框架设计数据访问层,PackageInstance对象的示例POCO结构为
public class PackageInstance
public virtual long PackageInstanceId set;get;
public virtual boolean IsDeleted set;get;
public virtual List<Session> Sessions set;get;
public class Session
public virtual long SessionId set;get;
public virtual long PackageInstanceId set;get;
public virtual boolean IsDeleted set;get;
public virtual List<Note> Notes set;get;
public class Note
public virtual long NoteId set;get;
public virtual long SessionId set;get;
public virtual boolean IsDeleted set;get;
public virtual List<Documents> Document set;get;
我需要在单个方法调用中加载 PackageInstance 对象及其子对象,而不是单独加载每个对象。
var packageInstanceDB = entity.PackageInstances.First(p => p.PurchaseSessionId == purhcaseSessionId);
//There is a DB call happening here to load the Session.
packageInstanceDB.Sessions.Where(s=>!s.IsActive).ForEach(s =>
//Again there is a DB call happening here to load the associated session notes.
s.Notes.Where(sn => !sn.IsDeleted).ToList().ForEach(sd=>
//Again there is a DB call happening here to load the associated note documents.
sd.Documents.Where(doc=>!doc.IsDeleted));
);
这里如何消除多个DB调用?
【问题讨论】:
你的代码被编译了吗? 强乐。用实际的代码快照更新了问题。这里也发生了多个数据库调用。 你能给我们举个例子并解释一下你想得到什么吗? 【参考方案1】:免责声明:我是项目的所有者Entity Framework Plus
EF+ Query IncludeFilter 功能允许过滤相关实体。支持EF5
var packageInstanceDB = entity.PackageInstances
.IncludeFilter(x => x.Sessions)
.IncludeFilter(x => x.Sessions.Select(y => y.Notes.Where(sn => !sn.IsDeleted)))
.IncludeFilter(x => x.Sessions.SelectMany(y => y.Notes.Where(sn => !sn.IsDeleted)).Select(z => z.Documents.Where(sn => !sn.IsDeleted)))
.First(p => p.PackageInstanceId == purhcaseSessionId);
注意:必须包含每个路径
维基:EF+ Query IncludeFilter
【讨论】:
首先要感谢 Jonathan Magnan... 4 个月前,我用 EFP 替换了现有代码,它提供了更好的性能.....以上是关于在实体框架中加载具有过滤条件的子对象记录的主要内容,如果未能解决你的问题,请参考以下文章