Eager Loading, Lazy Loading And Explicit Loading In Entity Framework

In this post, we will be discussing about Eager Loading, Lazy Loading and Explicit Loading in an Entity Framework. All three terms -- Eager Loading, Lazy Loading and Explicit Loading -- refer to the process of loading the related entities. They define when to load the related entities or child entities.

Eager Loading

Eager Loading helps you to load all your needed entities at once; i.e., all your child entities will be loaded at single database call. This can be achieved, using the Include method, which returs the related entities as a part of the query and a large amount of data is loaded at once.

For example, you have a User table and a UserDetails table (related entity to User table), then you will write the code given below. Here, we are loading the user with the Id equal to userId along with the user details.

It is the default behavior of an Entity Framework, where a child entity is loaded only when it is accessed for the first time. It simply delays the loading of the related data, until you ask for it.

For example, when we run the query given below, UserDetails table will not be loaded along with the User table.

User usr = dbContext.Users.FirstOrDefault(a => a.UserId == userId);

It will only be loaded when you explicitly call for it, as shown below.

UserDeatils ud = usr.UserDetails; // UserDetails are loaded here

Explicit Loading

There are options to disable Lazy Loading in an Entity Framework. After turning Lazy Loading off, you can still load the entities by explicitly calling the Load method for the related entities. There are two ways to use Load method Reference (to load single navigation property) and Collection (to load collections), as shown below.

User usr = dbContext.Users.FirstOrDefault(a => a.UserId == userId);

dbContext.Entry(usr).Reference(usr => usr.UserDetails).Load();

When to use what

Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.

Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere.

Use Lazy Loading when you are using one-to-many collections.

Use Lazy Loading when you are sure that you are not using related entities instantly.

When you have turned off Lazy Loading, use Explicit loading when you are not sure whether or not you will be using an entity beforehand.