New Features Of Entity Framework Core 2.1 - Lazy Loading

Eager Loading

 
In contrast to lazy loading, eager loading loads all entities related with parent entity automatically. Lazy loading is not supported in legacy versions so first, let us discuss eager loading as an example so that we can understand how beneficial lazy loading is. The below example is created with Entity Framework Core 2.0.
  1. public class User  
  2.     {  
  3.       
  4.         [Key]  
  5.         public int UserId { getset; }  
  6.         public string UserName { getset; }  
  7.   
  8.         public virtual ICollection<Post> Post { getset; }  
  9.   
  10.     }  
  11.   
  12.   public class Post  
  13.     {  
  14.          
  15.         [Key]  
  16.         public int PostId { getset; }  
  17.         public string Title { getset; }  
  18.         public DateTime CreatedOn { getset; }  
  19.         public string Content { getset; }  
  20.         public virtual User User { getset; }  
  21.   
  22.     }  
Here is a small code for Eager Loading.
  1. static void Main(string[] args)  
  2.        {  
  3.            var db = new TestDbContext();  
  4.            User usr = db.Users.Include(p => p.Post ).Where(u => u.UserId == 1).FirstOrDefault();  
  5.   
  6.            foreach (var post in usr.Post)  
  7.                Console.WriteLine(post.Title);  
  8.   
  9.        }  
As soon as line 14 is executed, the SQL Server Profiler shows 2 queries on 2 entities executed.
 
New Features Of Entity Framework Core 2.1 - Lazy LoadingNew features of Entity Framework Core 2.1 - Lazy Loading
 
New Features Of Entity Framework Core 2.1 - Lazy LoadingNew features of Entity Framework Core 2.1 - Lazy Loading
 
You can see in the profiler that related entities are also loaded immediately. This immediate loading can be stopped, and called when needed, with lazy loading.
 

Lazy Loading

 
Lazy Loading is the default behavior of LINQ that’s why it is the default behavior of EF Core. With lazy loading, all related entities are not loaded along with the parent entity automatically. For example: If the User entity has a foreign key in the Post entity. With lazy loading, only the User’s data would be loaded, the Post entity would be loaded on demand.
 
Lazy loading is useful when the relationship between entities is a one-to-many relationship and you are sure that related entities are not used instantly. It can help in performance; for example, if you have huge data, then with the help of lazy loading, you can reduce application startup time, lessen the memory usage, and reduce the load on DBMS (fewer queries to the server in a time). Lazy loading is not supported by legacy EF Core versions, so we would discuss an example with Entity Framework Core 2.1 only.
 
Install Microsoft.EntityFrameworkCore.Proxies NuGet package and make changes to your Context class. Just add "UseLazyLoadingProxies".
  1. class TestDbContext : DbContext  
  2.     {  
  3.         public DbSet<Post> Posts { getset; }  
  4.         public DbSet<User> Users { getset; }  
  5.   
  6.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  7.         {  
  8.             optionsBuilder.UseLazyLoadingProxies(); // Notice this change  
  9.   
  10.             optionsBuilder.UseSqlServer(@"Server=MUKESHTest;Database=Test2.1;Trusted_Connection=True;");  
  11.         }  
  12.     }  
Remove Eager Loading by removing "include" and use Lazy Loading.
  1. static void Main(string[] args)  
  2.         {  
  3.             var db = new TestDbContext();  
  4.             var usr = db.Users.Where(u => u.UserId == 1).FirstOrDefault();  
  5.             Console.WriteLine("Now, loading related entities");  
  6.   
  7.   
  8.             foreach (var post in usr.Post)  
  9.                 Console.WriteLine(post.Title);  
  10.         }  
When we run the above code, the Profiler after line 14 looks like the following.
 
New Features Of Entity Framework Core 2.1 - Lazy LoadingNew features of Entity Framework Core 2.1 - Lazy Loading 
 
New Features Of Entity Framework Core 2.1 - Lazy LoadingNew features of Entity Framework Core 2.1 - Lazy Loading
 
When we run to line 17, we see related entities loading.
 
New Features Of Entity Framework Core 2.1 - Lazy LoadingNew features of Entity Framework Core 2.1 - Lazy Loading
 
New Features Of Entity Framework Core 2.1 - Lazy LoadingNew features of Entity Framework Core 2.1 - Lazy Loading
 

Conclusion

 
We can see in the above example that it is easy to stop the loading of related entities. It is a really nice and a well-needed feature in Entity Framework Core 2.1.


Similar Articles