Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top