Entity Framework - Eager Loading


Eager loading is the process where a query for one type of entity also loads related entities as part of the query. Eager loading loads the related data in scalar and navigation properties along with query result at first shot. Eager loading is achieved by use of the Include method.
Include is a query builder method and you can apply it to an ObjectQuery or ObjectSet type of EntitySet.
 

For example, the following queries will load books and all the publishers related to each book.

using (var context = new BooksContext()) 
{ 
    // Load all books and related publishers 
    var books1 = context.Books 
                          .Include(b => b.Publisher) 
                          .ToList(); 
 
    // Load one books and its related publisher 
    var book1 = context.Books 
                        .Where(b => b.Name == "ASP.NET") 
                        .Include(b => b.Publisher) 
                        .FirstOrDefault(); 
 
    // Load all books and related publishers using a string to specify the relationship 
    var books2 = context.Books 
                          .Include("Publisher") 
                          .ToList(); 
 
    // Load one book and its related publisher using a string to specify the relationship 
    var book2 = context.Books 
                        .Where(b => b.Name == "ASP.NET") 
                        .Include("Publisher") 
                        .FirstOrDefault(); 
}

 

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More