Explaining Lazy Loading in Entity Framework

Lazy loading is concept where objects are loaded on demand & not at on the go.
Lets Take Example of Company which is having many departments & each department has many employees.

Var departments = context.Departments.ToList();

foreach(department in departments)    // here only department object is loaded.
{
  foreach (employee in department.employees)   // here employee object is loaded.
    {
	
    }
}

Here in 1st foreach loop only department object will be loaded & in 2nd foreach loop employee object will be loaded.

By default Lay Loading is enabled in Entity Framework.It can be turned of LazyLoadingEnabled property to false.

context.ContextOptions.LazyLoadingEnabled = false;

After this we can explicitly write which object we want to load with its parent object like bellow.

var Departments = context.departments.Include(“employees”);

Here it will load Department & its related Employee objects on the go.

admin