a blog for those who code

Friday 14 April 2017

How to load Related Entities in Entity Framework

In this post we will be discussing about loading related entities in Entity Framework. Entity Framework offers three ways to load related entities or object and they are Eager Loading, Lazy Loading and Explicit Loading. All the three i.e. Eager Loading, Lazy Loading and Explicit Loading are used to load related entities and can be used wherever it is applicable.

Eager Loading : In Eager Loading all the related entities are loaded at once along with the original entity. Eager Loading is achieved using Include() method. In the below example we will load UserDetails Table along with User table.

//Usage
var user = dbContext.Users.Include(a=>a.UserDetails)
   .Where(user => user.UserId == userid)
   .SingleOrDefault();
return user;

When you are sure that you will be using the child entities in future along with the parent entities you should use the above method of loading the related entities.

Lazy Loading : One of the important functions of Entity framework is to take advantage of Lazy Loading. Lazy loading means delaying of loading the related data until you required them.

//Usage
var user = dbContext.Users.Where(user => user.UserId == userid).SingleOrDefault();
var firstUserDetails = user.Select(user => user.UserDetails).FirstOrDefault();

In the above code when we call the UserDetails, a related entity of User, will not be loaded. It will be loaded only when we specifically need it i.e. in the 2nd line.

Explicit Loading : In Entity Framework its possible to turn off the Lazy Loading. Now after turning off the Lazy Loading, if you want to have certain related entities you can use Explicit Loading. Explicit Loading is a way to load related entities where you have to explicitly load the related entities as shown below :

//Usage
var user = dbContext.Users.Where(user => user.UserId == userid).SingleOrDefault();
var firstUserDetails = user.UserDetails.Load();

If you know that you required related entities you should use Eager Loading instead of Lazy Loading and Explicit Loading because lazy loading will fire a lot of queries when you will load related entities whereas in Eager Loading you just need to fire single query and all the related entities will be loaded at once. In both Lazy Loading and Explicit Loading there will be a lot of round trips to the database to load the entities whereas in Eager Loading it just one call.

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment