Workaround for Multiple Database Queries for Parent-Child Entity Relationship Loading

Developer
Nov 9, 2012 at 12:42 PM
Edited Nov 9, 2012 at 12:50 PM

Issue: If an entity (let's call it ParentEF) has one or more Navigation Properties with the Csla Getter and Csla Setter set to "Public" and LazyLoadingEnabled = "True", then a separate database query is performed for each distinct value that is a foreign key to the Navigation Property object (let's call one ChildEF). These additional database queries could become significant when the data in your tables becomes large and this could result in poor runtime performance for your application due to the excessive use of the database. 


Workaround:  Create a separate partial class for the entity's business collection object (let's call the generated entity's business collection object ParentEFList and the additional partial class' name as ParentEFList1). In ParentEFList1, one could add a subroutine as follows to allow all the ParentEF and ChildEF data to be retrieved from the database all at once. (Note, the string "ChildEFs" in the Include statement refers to the name of the Navigation Property in ParentEF.

public partial class ParentEFList : Csla.BusinessListBase<ParentEFList, ParentEF>
{
   public void Fetch_ParentChild()
   {
      using (var ctx = Csla.Data.ObjectContextManager<CslaExtensionProject.SampleDBCslaExtensionsEntities>.GetManager(SampleDBCslaExtensionsModel.SampleDBCslaExtensionsEntitiesDatabase .Name))
      {
         var data = ctx.ObjectContext.ParentEFs.Include("ChildEFs");
         ReadData(data);
      }
   }
   ...
}

To use the subroutine to populate my business collection object in a .Net form, one could use the code:

SampleDBCslaExtensionsModel.ParentEFList parentEFList = SampleDBCslaExtensionsModel.ParentEFList.New(); 
parentEFList.Fetch_ParentChild(); 
In the case of a parent-child-grandchild relationship (let's call the grandchild Navigation Property GrandchildEFs), one could add the following subroutine to the ParentEFList1 class:

public void Fetch_ParentChildGrandchild()
{
   using (var ctx = Csla.Data.ObjectContextManager<CslaExtensionProject.SampleDBCslaExtensionsEntities>.GetManager(SampleDBCslaExtensionsModel.SampleDBCslaExtensionsEntitiesDatabase.Name))
   {
      var data = ctx.ObjectContext.ParentEFs.Include("ChildEFs.GrandchildEFs");
      ReadData(data);
   }
}

and use the subroutine to populate your business collection object with the following code:

SampleDBCslaExtensionsModel.ParentEFList parentEFList = SampleDBCslaExtensionsModel.ParentEFList.New();
parentEFList.Fetch_ParentChildGrandchild();