liveBook · Manning

Eager loading

As explained in .NET in Action, Second Edition

Eager loading retrieves an entity and specified related entities as part of the same query operation.

Eager loading retrieves an entity and specified related entities during the same query operation. In Entity Framework Core, call Include for each relationship that should appear in the returned objects. section 5.2.3

Use eager loading when:

  • A query needs Books together with their Ratings immediately. section 5.2.3
  • Multiple relationships must be returned; add a separate Include for each relationship. section 5.2.3
  • You prefer one query that returns more data over deferred relationship retrieval. section 5.2.3

Loading books with ratings

foreach (var book in dbContext.Books.Include(b => b.Ratings)) { Console.WriteLine($"Book \"{book.Title}\" has id {book.Id}"); book.Ratings.ForEach(r => Console.WriteLine($"\t{r.Stars} stars: {r.Comment ?? \"-blank-\"}")); } section 5.2.3

Listing 5.15 Printing all Books with their Ratings to the console
using Microsoft.EntityFrameworkCore;                             #1
  
// ...
  
foreach (var book in dbContext.Books
           .Include(b => b.Ratings))                             #2
{
  Console.WriteLine($"Book \"{book.Title}\" has id {book.Id}");
  book.Ratings.ForEach(r =>                                      #3
    Console.WriteLine(
    $"\t{r.Stars} stars: {r.Comment ?? "-blank-"}"));            #4
}

Inspect the complete C# example showing the Include call and iteration over loaded ratings. section 5.2.3

How .NET in Action, Second Edition covers it

How deep it goes
Explains Include, multiple relationships, and query trade-offs, but defers explicit and select loading.
Examples
Demonstrates loading Books with Ratings and printing each rating’s stars and comment.
What it assumes
Assumes Entity Framework Core entities with relationships such as Book and Rating.
What you can do after
Apply it via Entity Framework Core by adding Include expressions to relationship queries.
How it connects
Connects eager loading with Entity Framework Core, relationships, navigation properties, lazy loading, explicit loading, and select loading.

Also explained in

Compare how 2 books explain eager loading →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.