Lazy Loading vs Eager 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:
- Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.
- 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:
- Use Lazy Loading when you are using one-to-many collections.
- 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.
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.
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.
I think it is good to categorize relations like this
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.
Note: like Transcendent said there may be disposal problem with lazy loading.