Loading related entities in EF


Loading related entities in EF

Entity Framework supports the following three methods to load related data.

  1. Eager Loading
  2. Lazy Loading
  3. Explicit Loading

Eager Loading

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method.

In Eager Loading, all relevant data for an entity is loaded at the time of the query of the entity in the context object. Eager Loading can be done by using the "Include" method. To perform Eager Loading, Lazy Loading must be disabled. Lazy Loading is enabled by default in Entity Framework.

Eager Loading at multiple levels

We can also eagerly load multiple levels of related entities. In the following example, it loads the related entity Department, Employee Master and Detail.

Lazy Loading

Lazy Loading means delay loading the related entities. In Lazy Loading, a related entity or collection of entities is loaded from the database for the first time that a property is referred or the entity is accessed.

Disable Lazy 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.

Explicit Loading

If Lazy Loading is disabled then it is still possible to fetch the related entities without the use of Eager Loading. It is possible with Explicit Loading. To explicitly retrieve the related entities from the database we can use the "Load" method.

Query()

You can also write LINQ-to-Entities queries to filter the related data before loading. The Query() method enables us to write further LINQ queries for the related entities to filter out related data.

3