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

