Entity Framework Core Interview Question #42

What is the N+1 query problem?

Relationships, Navigation Properties & Loading Data Junior Beginner

Quick Interview Answer

The N+1 problem occurs when one query loads a set of parent records and then an additional query is executed for each parent to load related data.

Detailed Explanation

The N+1 problem occurs when one query loads a set of parent records and then an additional query is executed for each parent to load related data.

For example, loading 100 Orders and lazily loading Customer for every order can result in one query for the orders plus many additional queries.

Prevent it by designing the query deliberately with projection, appropriate Include usage, batching, or other query techniques. SQL logging and profiling are useful for detecting it.

Code Example

// Better: retrieve the required shape in one query.
var orders = await db.Orders
    .Select(o => new OrderListDto
    {
        Id = o.Id,
        CustomerName = o.Customer.Name,
        Total = o.Total
    })
    .ToListAsync();