Difference between Lazy Loading and Eager Loading

By | November 30, 2017

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

With Lazy Loading, we only retrieve just the amount of data, which we need in a single query. When we need more data related to the initial data, additional queries are issued to the database. This means there are several round trips between the Application Server and the database Server. In general, these database round trips are very often the major performance bottleneck in most Applications. Lesser the round trips, better will be the performance.

Example:-

var query = context.Categories.Take(3); // Lazy loading
 
foreach (var Category in query)
{
 Console.WriteLine(Category.Name);
 foreach (var Product in Category.Products)
 {
 Console.WriteLine(Product.ProductID);
 }
 }

You can turn off the lazy loading feature by setting LazyLoadingEnabled property of the ContextOptions on context to false as below code. After that you can fetch the related objects with the parent object in one query itself.

context.ContextOptions.LazyLoadingEnabled = false;

 

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.

With Eager Loading, all the data is retrieved in a single query, which can then be cached to improve the Application performance. With Eager Loading, we are trading memory consumption for the database round trips.

Example:-

var query = context.Categories.Include("Products").Take(3); // Eager loading
 
 foreach (var Category in query)
 {
 Console.WriteLine(Category.Name);
 foreach (var Product in Category.Products)
 {
 Console.WriteLine(Product.ProductID);
 }
 }

When to use eager loading:

  • In “one side” of one-to-many relations that you sure are used every where with main entity. like User property of an Article. Category property of a Product.
  • Generally When relations are not too much and eager loading will be good practice to reduce further queries on server.

When to use lazy loading:

  • Almost on every “collection side” of one-to-many relations. like Articles of User or Products of a Category
  • You exactly know that you will not need a property instantly.

I hope you will enjoy the Difference between Lazy Loading and Eager Loading. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Like it? Share it