Last post Jan 08, 2018 06:27 AM by Cathy Zou
Jan 06, 2018 07:43 PM|Manishamani|LINK
Jan 08, 2018 06:27 AM|Cathy Zou|LINK
Lazy Loading 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.
User usr = dbContext.Users.FirstOrDefault(a => a.UserId == userId);
It will only be loaded when you explicitly call for it, as shown below.
UserDeatils ud = usr.UserDetails; // UserDetails are loaded here
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.
User usr = dbContext.Users.Include(a => a.UserDetails).FirstOrDefault(a => a.UserId == userId);
If you have multiple level of child entities, then you can load, using the query given below.
User usr = dbContext.Users.Include(a => a.UserDetails.Select(ud => ud.Address)).FirstOrDefault(a => a.UserId == userId);
When to use what
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.
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.