Tuesday, October 20, 2015

Difference between Eager Loading, Lazy Loading & Explicit Loading

Eagerly Loading

This is the process to load all the related entities while loading an entity. When we load an entity, we will be loading all the related entities all together. We use Include method to achieve Eager Loading. For example following will load all the Categories + All the Products of those categories:

using (InventoryContext ctx = new InventoryContext())
{
    var cats = ctx.Categories.Include(b => b.Products).ToList();
}

We can load related entities up to n number of levels.

Lazy Loading

Lazy loading is a concept where we delay the loading of the object until the point at which it is needed. Means lazy loading does not allow to load objects unnecessarily objects will be loaded only when they are needed.

Lazy loading created problem with serialization. Serializers access each and every property to serialize. Hence all the related entities will load. This will increase the overhead and will result in a large result set. So it is advised to turn Lazy loading OFF when work with Serialization.

Explicitly Loading

This is the process to load related entities keeping serialization off. For this we need to make explicit call to load related entity.

No comments:

Post a Comment