IT:AD:EF/CodeFirst:HowTo:Queries/Include Nested Tables

Summary

There are a couple of different ways to do it.

Process

There's the old string way:

using (AppDbContext context = new AppDbContext())
{
var invoice = context.Invoices.Include("LineItems.Product").FirstOrDefault();
var product = invoice.LineItems.First().Product;
Debug.Assert(product!=null);
}

and the include/select:

Note how it can be nested indefinately…


using (AppDbContext context = new AppDbContext())
{
  var lineItem = context.Invoices
                        .Include(i => i.LineItems.Select(li => li.Product))
                        .FirstOrDefault();
  var product = invoice.LineItems.First().Product;
  Debug.Assert(product != null);
}