Reputation: 1433
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.
Upvotes: 8
Views: 6755
Reputation: 245389
You can always explicitly load your child collections:
var result = db.SomeTable.Include("SomeChildCollectionName")
.Include("AnotherChildCollectionName")
.ToList();
Upvotes: 14
Reputation: 12126
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.
Upvotes: 3