Eager loading with DbContext

Description and code samples
Table of Contents
Description

How it works

Entity Framework achieves eager loading on telling what related data to include when querying for an entity type. Entity Framework will then use a JOIN in the generated SQL to pull back all of the data in a single query: this is achieved using the DbSet.Include method.

The method uses a lambda expression to specify which properties to include the data for.
As more data is required to be included (refer to sample 4), the number of JOIN tables will increase and performance decreases.
Operations
Eager loading sample 1: Include a single set of related data
How to do it
  using (var context = new BreakAwayContext())
  {
    var allDestinations = context
      .Destinations
      .Include(d => d.Lodgings);

    foreach (var destination in allDestinations)
    {
      Console.WriteLine(destination.Name);

      foreach (var lodging in destination.Lodgings)
      {
        Console.WriteLine(" - " + lodging.Name);
      }
    }
  }

The code uses the Include method to indicate that the query for all entities “destination” should include the related “Lodging” data, by referencing the Destination.Lodgings property.

 

Eager loading sample 2: Include more than one set of related data
How to do it

Including one related set of data plus a specific property in a single query, can be achieved by “dotting through” the navigation properties in the lambda expression:

context.Lodgings
  .Include(l => l.PrimaryContact.Photo)
Eager loading sample 3: Include more than one set of related data (2)
How to do it

If in the path to be included contains a collection navigation property, the LINQ Select method must be used in order to identify which property should also be loaded:

context.Destinations
  .Include(d => d.Lodgings.Select(l => l.PrimaryContact))
Eager loading sample 4: Include more than one property
How to do it

If different data should be loaded then the Include method must be used multiple times in the same query to identify the different data to be loaded:

context.Lodgings
  .Include(l => l.PrimaryContact)
  .Include(l => l.SecondaryContact)
Eager loading sample 5: Using a LINQ Query
How to do it
The Include method can also be used in the context of a LINQ query.
If Query Sintax is used then
var query = from d in context.Destinations.Include(d => d.Lodgings)
            where d.Country == "Australia"
            select d;
If Method Sintax is used then
var query = context.Destinations
  .Include(d => d.Lodgings)
  .Where(d => d.Country == "Australia");
Eager loading sample 6: Using a LINQ Query (2)
How to do it

The Include method is as extension on IQueryable<T> and therefore can be added to a query at any point.

var query = from d in context.Destinations
            where d.Country == "Australia"
            select d;

query = query.Include(d => d.Lodgings);