How to use Lazy loading and Earger loading in Entity Framework

By FoxLearn 8/1/2024 2:39:26 AM   229
Entity Framework (EF) supports both lazy loading and eager loading to manage how related entities are loaded.

In these 3 concepts, we all refer to loading related entities.

Eager Loading

Eager loading lets you load all entities in a statement, all child entities will be loaded in a single call. This can be done via the Include method, which will return related entities as part of the query and a large amount of data will be loaded once.

For example, if you have a User and a UserDetails table (this table links to the User table), then you will write the code as shown below. We will load the user data with UserId in the UserDetails table.

User obj = dbContext.Users.Include(a => a.UserDetails).FirstOrDefault(a => a.UserId == userId);

If there are more levels we can use the following statement:

User obj = dbContext.Users.Include(a => a.UserDetails.Select(ud => ud.Address)).FirstOrDefault(a => a.UserId == userId);

Lazy Loading

This is the default of Entity Framework, where child entities are loaded only when they are first accessed. Simply defer the loading of the data at the relevant entity until you request it.

For example, when we run the command below, the UserDetails table will not load the User table:

User obj = dbContext.Users.FirstOrDefault(a => a.UserId == userId);

It is only loaded when you call it:

UserDeatils detail = obj.UserDetails; // UserDetails are loaded here

Consider another example:

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

public List<Person> GetPerson(){
    using(DbEntities db = new DbEntities()){
       return db.Person.ToList();
    }
}

After the GetPerson() method is called, you can't use lazy loading to access the employer property to retrieve an Employer object outside the method. Why? Because the db object was destroyed after exiting the using block. So you must use Person.Include (x => x.employer) to pre-load Employer's data into the person property before the db object is destroyed.

Explicit Loading

There are many options to disable the Lazy loading feature in Entity Framework. After turning off Lazy Loading, you can still load the related entity by explicitly calling Load() method to download related entities. There are two ways to use the LoadReference and Collection methods.

User obj = dbContext.Users.FirstOrDefault(a => a.UserId == userId);  
dbContext.Entry(obj).Reference(obj => obj.UserDetails).Load();   

So when to use it.

- Use Eager loading when the relationship is not too much. So Eager loading is a way to reduce the amount of queries to the server because there is only one query.

- Using Eager loading when you are sure you will use entities associated with the main entity in many places and many times.

- Use Lazy loading when you use 1-N relations

- Use Lazy loading when you are sure you do not use the related entity immediately.

- When you turn off the Lazy loading feature, use Explicit loading when you are not sure if you will use the previous entity.