What is the N+1 query problem in EF Core, and how does eager loading with Include() solve it?
Short answer
The N+1 problem occurs when code queries a list of N entities, then separately queries related data for each one individually inside a loop, resulting in 1 initial query plus N additional queries (N+1 total) instead of a single efficient join -- Include() (and ThenInclude() for…
Advertisement
AModel answer
The N+1 problem occurs when code queries a list of N entities, then separately queries related data for each one individually inside a loop, resulting in 1 initial query plus N additional queries (N+1 total) instead of a single efficient join -- Include() (and ThenInclude() for nested relations) instructs EF Core to eagerly load related entities as part of the original query via a SQL JOIN, collapsing what would be N+1 round-trips into one.
// N+1 problem: 1 query for orders, then N queries for each order's customer
var orders = await context.Orders.ToListAsync();
foreach (var order in orders) {
Console.WriteLine(order.Customer.Name); // lazy-loads Customer, one query per order!
}
// Fixed with eager loading: exactly 1 query total
var orders = await context.Orders.Include(o => o.Customer).ToListAsync();Real-world example
A dashboard page loading noticeably slowly under load is diagnosed via query logging to be issuing over 200 separate database round-trips for a list of 200 orders; adding a single .Include(o => o.Customer) collapses this to one query and dramatically improves response time.
Likely follow-ups
- How does query logging help you detect N+1 problems in existing code?
- What's the difference between eager, lazy, and explicit loading strategies?
Related topics