LINQ: cache with (child) collection properties

By default, because of the “Lazy Loading” setting, LINQ won’t load the child properties collection data until they are first accessed. So for the caching purpose, we have to force it to load everything before releasing the DataContext.  This is what you should do:

public static List<ParentObject> GetPremiumsByCompany(int companyID)
{
using (PolicyDataSourceDataContext db = new PolicyDataSourceDataContext())
{
db.ObjectTrackingEnabled = false; //optional. only if the data is readonly
// have to set options otherwise the collection will not be populated
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<ParentObject>(p => p.ChildObject);
db.LoadOptions = dlo;

List<ParentObject> ret = (from pre in db.ParentObjects
select pre).ToList();
return ret;
}
}

Advertisements
This entry was posted in ASP.NET and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s