ASP.NET Core Web API Interview Question #113

What is the N+1 query problem?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

The N+1 problem occurs when one query loads a collection and then additional queries are executed separately for each item, producing many database round trips. This can cause severe performance degradation as result size grows.

Detailed Explanation

The N+1 problem occurs when one query loads a collection and then additional queries are executed separately for each item, producing many database round trips. This can cause severe performance degradation as result size grows.

Avoid it by designing queries intentionally using projection, appropriate eager loading, aggregation, or other set-based techniques.

Code Example

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