Lazy loading using Entity Framework

entity entity-framework

Question

using(DataContext db = new DataContext ())
{
    var result = db.SomeTable.ToList();
    return result;
}

Problem is after i have returned the result, the connection is closed and because its closed, it crashes when i am trying to access any of the child elements. That happens because with lazy loading set to True ( default ) it never loads the child relations before they are used and i start using them AFTER the connection is closed. So how is the best way to solve this?

I have tried to turn off the lazy loading but then it didnt load any of the child relation tables.

1
8
11/3/2011 2:44:00 AM

Accepted Answer

You can always explicitly load your child collections:

var result = db.SomeTable.Include("SomeChildCollectionName")
                         .Include("AnotherChildCollectionName")
                         .ToList();
14
1/10/2011 2:42:00 PM

Popular Answer

You can use the .include() method.

var result = db.SomeTable.Include("ChildEntitySet").ToList();

You can also add a result.ChildEntitySet.Load() call before returning. This is less efficient as it will result in two trips to the server. Using the .Include() method will generate a SQL Statement with a JOIN allowing only one trip to the server.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow