Eager , Lazy and explicit loading in EF6

If this small resume is true ?

Yes.

If it is true, what is the difference between eager and explicit loading?

Eager loading is the opposite of Lazy loading but Explicit loading is similar to lazy loading, except that: you explicitly retrieve the related data in code; it doesn’t happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity.

From techblog:

Eager Loading :

Eager loading is the opposite of Lazy loading which is : The process
of loading a specific set of related objects along with the objects
that were explicitly requested in the query.

Explicit Loading :

Explicit loading is defined as : when objects are returned by a query,
related objects are not loaded at the same time. By default, they are
not loaded until explicitly requested using the Load method on a
navigation property.

And:

If I Use lazy loading and I call for example dpc_gestion.dpc_participant, does the navigation properties loads?or I will get an exception?

You don’t get any exception and the navigation properties should loads.

Is there a case when eager loading or explicit loading were better
than lazy loading in performance and responsiveness?

Eager loading is typically more efficient when you need the related data for all retrieved rows of the primary table. And also when relations are not too much, eager loading will be good practice to reduce further queries on server. But when you know that you will not need a property instantly then lazy loading maybe a good choice. And also eager loading is a good choice in a situation where your db context would be disposed and lazy loading could not take place anymore. For example consider the following:

public List<Auction> GetAuctions()
{
    using (DataContext db = new DataContext())
    {
        return db.Auctions.ToList();
    }
}

After calling this method, You cannot load the related entity lazily because the db is disposed and so the Eager Loading would be a better choice here.

One more thing to note is: Lazy loading will produce several SQL request while Eager loading load data with one request. Eager loading is also a good choice to solve the n+1 selects issue in ORMs.
Have a look at this post: What is the n+1 selects issue?

Leave a Comment