Tuesday, 24 May 2016

What are lazy/deferred loading and eager loading?



Lazy/Deferred Loading: In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

DataContext context = new DataContext();
var query = context.Department.Take(3); // Lazy loading
foreach (var Dept in query)
{
  Console.WriteLine(Dept.Name);
  foreach (var Emp in Dept.Employee)
  {
    Console.WriteLine(Emp.EmpID);
  }
}



DataContext context = new DataContext();
var query = context.Department.Include("Employee").Take(3); // Eager loading
foreach (var Dept in query)
{
  Console.WriteLine(Dept.Name);
  foreach (var Emp in Dept.Employee)
  {
   Console.WriteLine(Emp.EmpID);
  }
}

No comments:

Post a Comment