Download complete project : LazyLoadingEagerLoading.zip
The Entity Framework offers several different ways to load the entities that are related to your target entity. For example, when you query for Employee, there are different ways that the related Employee Addresses will be loaded into the Object State Manager. From a performance standpoint, the biggest question to consider when loading related entities will be whether to use Lazy Loading or Eager Loading.
Eager Loading – “do all the work in advance”
When using Eager Loading, the related entities are loaded along with your target entity set. You use an Include statement in your query to indicate which related entities you want to bring in.
Lazy Loading – “don’t do the work until you absolutely have to.”
When using Lazy Loading, your initial query only brings in the target entity set. But whenever you access a navigation property, another query is issued against the store to load the related entity that means Related/child objects are not loaded automatically when a navigation property is accessed.Once an entity has been loaded, any further queries for the entity will load it directly from the Object State Manager. you can also turn off lazy loading for a particular property or an entire 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:
this.Configuration.LazyLoadingEnabled = false; Rules for lazy loading:
- context.Configuration.ProxyCreationEnabled should be true.
- context.Configuration.LazyLoadingEnabled should be true.
- Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual.
Let’s start with actual implementation.Create Console Application with name LazyEagerLoading.
Step 1: Create Poco classes for employee and employeeAddress. Step 2: Create EmployeeContext and EmployeeDbInitilizer classes. Step 3: As per the above code, i am trying to get employee details using the employeecontext class and then iterate through the employee item also try to read navigation property EmployeeAddresses. If you try to debug the code and find that details for parent and child related tables comes at one time but this is not correct.Actually some thing different activity happens at back end and there are several sql query executed to get the details and to track this activity i have used sql profiler. you can see code for lazy loading and outcome of the code:
Now run the application. In the code above, note the first for-each loop, the data of only the main entity, the Employee, is loaded but not that of the EmployeeAddresses. The data of the related entity is loaded when the nested foreach loop is executed. Analysis report of sql profiler for above code execution: Here you can see that there are four different queries executed to fetch the details from the database. first query executed to get employee details and other three queries executed to fetch the details of navigation property that is EmployeeAddress.This means that to fetch the data of the related entity, database calls are being made again and again, after the data for main entity has been fetched, that could negatively hamper the efficiency of the application.
EagerLoading: Step 4: To implement the eager loading we have to make two changes in our existing code. first change in employeeContext class and second in our program.cs . Add below statement in employeeContext constructor:
this.Configuration.LazyLoadingEnabled = false;
Step5 : Include related entity with main entity at the time of query execution. Snippet
var query = ContextObj.Employees.Include("EmployeeAddresses").ToList();
Step 6: Now again execute above code,see output and track background process with sql profiler. now you can see output is still same as lazy loading but there is a major difference in sql profile analysis report. this time only single query executed to get the parent and child entity details while in lazy loading example different queries initiate to fetch the details.
You will see the query at the bottom of the selection that shows the join being applied at the back-end by the SQL Server. This is known as Eager Loading which means loading the related entity data along with the data of the main entity. Now the question arises when to use what option:
Do you need to access many navigation properties from the fetched entities?
No Both options will probably do. However, if the payload your query is bringing is not too big, you may experience performance benefits by using Eager loading as it’ll require less network round trips to materialize your objects. Yes If you need to access many navigation properties from the entities, you’d do that by using multiple include statements in your query with Eager loading. The more entities you include, the bigger the payload your query will return. Once you include three or more entities into your query, consider switching to Lazy loading.
Do you know exactly what data will be needed at run time?
No Lazy loading will be better for you. Otherwise, you may end up querying for data that you will not need. Yes Eager loading is probably your best bet; it will help loading entire sets faster. If your query requires fetching a very large amount of data, and this becomes too slow, then try Lazy loading instead.
Is your code executing far from your database? (increased network latency)
No When the network latency is not an issue, using Lazy loading may simplify your code. Remember that the topology of your application may change, so don’t take database proximity for granted. Yes When the network is a problem, only you can decide what fits better for your scenario. Typically Eager loading will be better because it requires fewer round trips.