Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework lazy loading

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.

like image 249
syncis Avatar asked Jan 10 '11 14:01

syncis


People also ask

What is Entity Framework lazy loading?

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.

Does Entity Framework support lazy loading?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

How do I stop lazy loading in Entity Framework?

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.

What is lazy loading in Entity Framework Core?

Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.


2 Answers

You can always explicitly load your child collections:

var result = db.SomeTable.Include("SomeChildCollectionName")
                         .Include("AnotherChildCollectionName")
                         .ToList();
like image 107
Justin Niessner Avatar answered Oct 25 '22 16:10

Justin Niessner


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.

like image 23
DCNYAM Avatar answered Oct 25 '22 17:10

DCNYAM