Entity Framework Core Interview Question #131

What is the N+1 query problem and how can it be avoided?

Performance, Raw SQL, Stored Procedures & Advanced Queries Senior Advanced

Quick Interview Answer

The N+1 problem occurs when one query retrieves a collection and an additional query is then executed for each item to load related information. It commonly appears with careless lazy loading or explicit loading inside loops. Avoid it with projection, suitable Include operations, batching, or another set-based query shape. Database-command logging can reveal repeated queries.

Detailed Explanation

The N+1 problem occurs when one query retrieves a collection and an additional query is then executed for each item to load related information. It commonly appears with careless lazy loading or explicit loading inside loops. Avoid it with projection, suitable Include operations, batching, or another set-based query shape. Database-command logging can reveal repeated queries.

Code Example

var orders = await db.Orders
    .Select(o => new OrderListDto
    {
        Id = o.Id,
        CustomerName = o.Customer.Name,
        ItemCount = o.Items.Count
    })
    .ToListAsync();