Explicit Loading in Entity Framework

Explicit Loading is a technique we query and load the related entities with an explicit call. Explicit loading works very similar to Lazy Loading, but the loading of the related entities happens only after an explicit call. The loading only when we invoke the Load method of the related entity’s DBEntityEntry object. In eager loading, we query the related entities along with the main entity in a single Query. In Lazy loading, EF loads the load related entities whenever we access the related Property.

Explicit Loading in Entity Framework

To make an explicit call to load a related entity, we use the Load method of the related entity’s DBEntityEntry object. This object provides information about the entity. The DBContext.Entry() method returns the DBEntityEntry of a given entity

In the following query, we retrieve five products from the database. Inside the for loop, we use the load method to retrieve the ProductModel Note use the Reference method as the ProductModel reference navigational property.

The corresponding SQL

The EF Generates the following Query in the load method.

Loading Collections

We use the reference method if the navigation property is of reference type. In the case of collection navigation property, the collection method is to be used

The Products is a collection navigation property the entity ProductModel. The following example retrieves the ProductModel and then uses the load method to explicitly load the Products. Since it is a collection navigation property we make use of the Collection method

The SQL Queries

Explicit Loading with Filtering

You can filter the output of load method by using Query and Load methods. For example, in the previous example, you may want to list only the product that has List Price > 30.

Virtual Property

You do not have the navigation properties as virtual.for the explicit loading to work.

Summary

Explicit Loading uses the Load method of the DBEntityEntryto load related data. Here you have full control over how & when the query is sent to the database. You can also filter the query using where before sending it to the database.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top