You are on page 1of 6

In this post, we will be discussing about Eager Loading, Lazy Loading and Explicit

Loading in an Entity Framework. All three terms -- Eager Loading, Lazy Loading and
Explicit Loading -- refer to the process of loading the related entities. They define
when to load the related entities or child entities.

Eager Loading

Eager Loading helps you to load all your needed entities at once; i.e., all your child
entities will be loaded at single database call. This can be achieved, using the
Include method, which returs the related entities as a part of the query and a large
amount of data is loaded at once.

For example, you have a User table and a UserDetails table (related entity to User
table), then you will write the code given below. Here, we are loading the user with
the Id equal to userId along with the user details.

1. User usr = dbContext.Users.Include(a => a.UserDetails).Fir


stOrDefault(a => a.UserId == userId);

If you have multiple level of child entities, then you can load, using the query given
below.

1. User usr = dbContext.Users.Include(a => a.UserDetails.Sele


ct(ud => ud.Address)).FirstOrDefault(a => a.UserId == user
Id);
Lazy Loading

It is the default behavior of an Entity Framework, where a child entity is loaded only
when it is accessed for the first time. It simply delays the loading of the related data,
until you ask for it.

For example, when we run the query given below, UserDetails table will not be
loaded along with the User table.

1. User usr = dbContext.Users.FirstOrDefault(a => a.UserId ==


userId);

It will only be loaded when you explicitly call for it, as shown below.

1. UserDeatils ud = usr.UserDetails; // UserDetails are loade


d here
Explicit Loading

There are options to disable Lazy Loading in an Entity Framework. After turning Lazy
Loading off, you can still load the entities by explicitly calling the Load method for the
related entities. There are two ways to use Load method Reference (to load single
navigation property) and Collection (to load collections), as shown below.
1. User usr = dbContext.Users.FirstOrDefault(a => a.UserId ==
userId);
2. dbContext.Entry(usr).Reference(usr => usr.UserDetails).Loa
d();

When to use what

1. Use Eager Loading when the relations are not too much. Thus, Eager
Loading is a good practice to reduce further queries on the Server.
2. Use Eager Loading when you are sure that you will be using related
entities with the main entity everywhere.
3. Use Lazy Loading when you are using one-to-many collections.
4. Use Lazy Loading when you are sure that you are not using related
entities instantly.
5. When you have turned off Lazy Loading, use Explicit loading when you
are not sure whether or not you will be using an entity beforehand.

In LINQ and Entity Framework, you have Lazy Loading and Eager Loading for
loading the related entities of an entity. In this article you will learn the
differences between these two 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.

For 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);
}
}

Generated SQL Query will be:


SELECT TOP (3)
[c].[CatID] AS [CatID],
[c].[Name] AS [Name],
[c].[CreatedDate] AS [CreatedDate]
FROM [dbo].[Category] AS [c]
GO

-- Region Parameters
DECLARE @EntityKeyValue1 Int = 1
-- EndRegion
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[CatID] AS [CatID],
[Extent1].[EntryDate] AS [EntryDate],
[Extent1].[ExpiryDate] AS [ExpiryDate]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[CatID] = @EntityKeyValue1
GO

-- Region Parameters
DECLARE @EntityKeyValue1 Int = 2
-- EndRegion
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[CatID] AS [CatID],
[Extent1].[EntryDate] AS [EntryDate],
[Extent1].[ExpiryDate] AS [ExpiryDate]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[CatID] = @EntityKeyValue1
GO
-- Region Parameters
DECLARE @EntityKeyValue1 Int = 3
-- EndRegion
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[CatID] AS [CatID],
[Extent1].[EntryDate] AS [EntryDate],
[Extent1].[ExpiryDate] AS [ExpiryDate]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[CatID] = @EntityKeyValue1
In above example, you have 4 SQL queries which means calling the database 4
times, one for the Categories and three times for the Products associated to
the Categories. In this way, child entity is populated when it is requested.
You can turn off the lazy loading feature by setting LazyLoadingEnabled
property of the ContextOptions on context to false. Now 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.

When to use eager loading

1. 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.
2. 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

1. Almost on every "collection side" of one-to-many relations. like Articles of User


or Products of a Category
2. You exactly know that you will not need a property instantly.
Note: like Transcendent said there may be disposal problem with lazy loading.
Eager Loading: Eager Loading helps you to load all your needed entities at once. i.e.
related objects (child objects) are loaded automatically with its parent object.

When to use:

1. Use Eager Loading when the relations are not too much. Thus, Eager Loading is
a good practice to reduce further queries on the Server.
2. Use Eager Loading when you are sure that you will be using related entities
with the main entity everywhere.
Lazy 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.

When to use:

1. Use Lazy Loading when you are using one-to-many collections.


2. Use Lazy Loading when you are sure that you are not using related entities
instantly.
NOTE: Entity Framework supports three ways to load related data - eager loading, lazy
loading and explicit loading.

29
Lazy loading will produce several SQL calls while Eager loading may load data with one
"more heavy" call (with joins/subqueries).

For example, If there is a high ping between your web and sql servers you would go with
Eager loading instead of loading related items 1-by-1 with lazy Loading.

16
Consider the below situation

public class Person{


public String Name{get; set;}
public String Email {get; set;}
public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){


using(EF.DbEntities db = new EF.DbEntities()){
return db.Person.ToList();
}
}
Now after this method is called, you cannot lazy load the Employer entity anymore. Why?
because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force
that to be loaded.
Eager Loading When you are sure that want to get multiple entities at a time, for
example you have to show user, and user details at the same page, then you should go
with eager loading. Eager loading makes single hit on database and load the related
entities.

Lazy loading When you have to show users only at the page, and by clicking on users
you need to show user details then you need to go with lazy loading. Lazy loading make
multiple hits, to get load the related entities when you bind/iterate related entities.

Lazy loading - is good when handling with pagination like on page load list of users
appear which contains 10 users and as the user scrolls down the page an API call brings
next 10 users. It's good when you don't want to load the entire data at once as it would
take more time and would give a bad user experience.

Eager loading - is good as other people suggested when there are not many relations
and fetch entire data at once in a single call to the database

// Using LINQ and just referencing p.Employer will lazy load


// I am not at a computer but I know I have lazy loaded in one
// query with a single query call like below.
List<Person> persons = new List<Person>();
using(MyDbContext dbContext = new MyDbContext())
{
persons = (
from p in dbcontext.Persons
select new Person{
Name = p.Name,
Email = p.Email,
Employer = p.Employer
}).ToList();
}

-3
It is better to use eager loading when it is possible, because it optimizes the performance of
your application.

ex-:

Eager loading

var customers= _context.customers.Include(c=> c.membershipType).Tolist();

lazy loading
In model customer has to define

Public virtual string membershipType {get; set;}


So when querying lazy loading is much slower loading all the reference objects, but eager
loading query and select only the object which are relevant.

You might also like