ASP.NET Core MVC Interview Question #146
What is the N+1 query problem and why can it hurt an MVC page?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
The N+1 problem occurs when an application executes one query to load a collection and then performs additional queries for individual items or related data. A page containing many rows can therefore trigger a large number of database round trips.
Detailed Explanation
The N+1 problem occurs when an application executes one query to load a collection and then performs additional queries for individual items or related data. A page containing many rows can therefore trigger a large number of database round trips.
Prevent it by designing the data query for the page, projecting only required fields, loading necessary relationships appropriately, and inspecting generated SQL and query counts when diagnosing performance.
Code Example
var products = await db.Products
.AsNoTracking()
.Select(p => new ProductListItem
{
Id = p.Id,
Name = p.Name,
CategoryName = p.Category.Name
})
.ToListAsync(token);