Using Entity Framework Core, how do you define which tables should be eager loaded?

Experience Level: Senior
Tags: Entity Framework

Answer

To define which tables should be eager loaded in Entity Framework Core, you can use the Include method to specify the related data to be included in the query. Here’s an example:

var orders = context.Orders.Include(o => o.Customer).ToList();
This code retrieves all orders and their associated customers in a single query.

You can also use the ThenInclude method to include additional levels of related data. Here’s an example:

var orders = context.Orders
    .Include(o => o.Customer)
        .ThenInclude(c => c.Address)
    .ToList();

This code retrieves all orders, their associated customers, and the addresses of those customers in a single query.
Entity Framework Core
Entity Framework Core

Are you learning Entity Framework ? Try our test we designed to help you progress faster.

Test yourself