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.
Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading means delaying the loading of related data, until you specifically request for it.
Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
We can disable lazy loading for a particular entity or a context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false.
Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.
You can always explicitly load your child collections:
var result = db.SomeTable.Include("SomeChildCollectionName")
.Include("AnotherChildCollectionName")
.ToList();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With