在实体框架中加载具有筛选条件的子对象记录

本文关键字:条件 对象 记录 筛选 框架 实体 加载 | 更新日期: 2023-09-27 18:27:04

用实体框架设计数据访问层,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调用?

在实体框架中加载具有筛选条件的子对象记录

免责声明:我是项目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);

注意:每个路径都必须包含

Wiki:EF+Query IncludeFilter