Eager Loading vs Lazy Loading vs Explicit Loading
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.
If you have multiple level of child entities, then you can load, using the query given below.
Lazy Loading 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.
It will only be loaded when you explicitly call for it, as shown below.
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.
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.
Last updated