VIJAY
VIJAY

Reputation: 849

Load child object records with filter condition in Entity Framework

Designed the Data Access Layer with Entity Framework and the Sample POCO Structure of PackageInstance object is

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;}
}

I need to load PackageInstance object along with his child objects in single method call, instead of loading each object separately.

  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));
  });

Here how to eliminate the multiple DB calls?

Upvotes: 0

Views: 320

Answers (1)

Jonathan Magnan
Jonathan Magnan

Reputation: 11327

Disclaimer: I'm the owner of the project Entity Framework Plus

EF+ Query IncludeFilter feature allow filtering related entities. It support 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);

Note: Every path must be included

Wiki: EF+ Query IncludeFilter

Upvotes: 1

Related Questions