Include tells Entity Framework Core to load a related navigation property while querying an entity. It follows the database relationship and assigns the related objects to that property. section 20.2
Use Include when the query needs related data from another table:
- Load an order's Lines collection with Include(o => o.Lines). section 9.3.4
- Continue into a nested relationship with ThenInclude(l => l.Product), loading each product associated with an order line. section 9.3.4
- Load a supplier's Products collection before returning the supplier from an API action. section 20.2
Without Include, related data spanning multiple tables requires additional queries and manual assembly. Include supplies the related objects as part of the query result, but the resulting object graph can contain circular references during JSON serialization. A Supplier can reference Products while each Product references its Supplier, causing an object-cycle exception in an ASP.NET Core response. section 9.3.4 section 20.2
Loading nested order data
public IQueryable<Order> Orders => context.Orders .Include(o => o.Lines) .ThenInclude(l => l.Product);
Listing 20.4 Related data in the SuppliersController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;
using Microsoft.EntityFrameworkCore;
namespace WebApp.Controllers {
[ApiController]
[Route("api/[controller]")]
public class SuppliersController : ControllerBase {
private DataContext context;
public SuppliersController(DataContext ctx) {
context = ctx;
}
[HttpGet("{id}")]
public async Task<Supplier?> GetSupplier(long id) {
return await context.Suppliers
.Include(s => s.Products)
.FirstAsync(s => s.SupplierId == id);
}
}
}
Inspect a complete controller action that loads a supplier and its Products collection with Include before returning the API response. section 20.2

