I've inherited some code and my current task is to improve it's performance. Straight away I've noticed a foreach loop containing lazy loads of child elements. I'm trying to remove the lazy loads since, in the example below, there's going to be 1 + (3 * n) calls to the database!
using (BaseEntityConnection BaseEntityContext = new BaseEntityConnection()) {
List<Parents> entities = BaseEntityContext.CallASproc(storeOrgLevelId, startDate, endDate).ToList<Parents>();
foreach (Parents entity in entities)
{
entity.Child1Reference.Load();
entity.Child2Reference.Load();
entity.Child3Reference.Load();
}
}
My initial thoughts turned to using .Include() but I don't see how that's possible when I'm initially calling a sproc. (Assume for the moment the sproc can't be generalised to Linq to entities.) I also thought that if I loaded the child entities using Linq to Entities before the call to the sproc then the tracking manager within the context would employ an 'Identity Map' to identify entities that are already loaded and therefore would figure out that it doesn't need to hit the database when I call .Load(). However, I guess I've also got to call .Attach() on each of the child references - but this seems clunky and I haven't made it work yet either!!
Does anybody know how I can get the object graph loaded for the entities returned by the sproc with the minimum of round-trips to the database?