Register now or log in to join your professional community.
Lazy loading is also known as deferred loading. Lazy loading is a technique, pattern where a data is loaded only on demand or only when it is required in order to increase the program efficiency, performance, etc.Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. Lazy loading is also called deferred loading or on-demand loading. It is called so because usually the data for an object will be loaded whenever it is initialized but in this technique, the loading is postponed or deferred till there is a requirement for the data. This is done when the data is really big or involves some sort of complexities in loading and it may not be used frequently.
Example:
using (var context = new MyContext()
{
//With Object Context by default lazyLoadingEnabled=false
context.ContextOptions.LazyLoadingEnabled = true;
//With DB Context
//context.Configuration.LazyLoadingEnabled = true;
Console.WriteLine("Lazy Lading Example....");
var dep = context.DepartmentMaster.Where(f => f.DepartmentID == 1).FirstOrDefault();
foreach (var emp in dep.EmployeeMaster)
{
Console.WriteLine("Code: " + emp.Code + " Email Address:" + emp.EmployeeDetail.PersonalEmail);
}
}
Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method.
Example:
using (var context = new MyContext())
{
Console.WriteLine("Eager Lading Example....");
var dep = context.DepartmentMaster.Include("EmployeeMaster.EmployeeDetail").Where(f => f.DepartmentID == 1).FirstOrDefault();
foreach (var emp in dep.EmployeeMaster)
{
Console.WriteLine("Code: " + emp.Code + " Email Address:" + emp.EmployeeDetail.PersonalEmail);
}
Console.ReadKey();
}
Lazy Loading: related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.
Eager Loading:In case of eager loading, related objects (child objects) are loaded automatically with its parent object. To use Eager loading you need to use Include() method.
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.
Eg: var query = context.Categories.Take(3);
EAGER LOADING: In case of eager loading, related objects (child objects) are loaded automatically with its parent object. To use Eager loading you need to use Include() method.
Eg: var query = context.Categories.Include(“Products”).Take(3);