Related Data Loading using EF Core – Part 3
In previous parts of related data loading we have seen how Eager and Explicit Loading works in EF Core. In this part we will cover brief details on Laze Loading technique.
Lazy Loading in EF Core :
Lazy loading is a technique of loading of related data by delaying it, until we specifically request for it.For example, Let’s assume a Employee entity contains the EmployeeAddress entity. In the Lazy loading, the dbcontext will first load the Employee data from the database and when we access the EmployeeAddress property, it will load EmployeeAddress data.
Here is the reference code to understand this better:
using (DBEntities context = new DBEntities())
{
//Loading Employees only
var employees = context.Employees.ToList();
Employee emp = employees[0];
//Loads Employee address only for selected Employee.
EmployeeAddress add = emp.EmployeeAddress;
}
Disabling Lazy Loading :
We can disable Lazy loading for a particular entity or a context.
– To turn off lazy loading for a property, do not make it virtual.
– To turn off lazy loading for all entities in the context, set its configuration property to false.