ASP.NET Core MVC Interview Question #191
How would you avoid N+1 queries when rendering an MVC list?
Senior Practical MVC Scenarios & Production Architecture Senior Advanced
Quick Interview Answer
Design one query around the data the view actually needs. Project related values into a list ViewModel so EF Core can translate the relationship access into appropriate SQL rather than executing a separate query for each row.
Detailed Explanation
Design one query around the data the view actually needs. Project related values into a list ViewModel so EF Core can translate the relationship access into appropriate SQL rather than executing a separate query for each row.
Inspect generated SQL and query counts when diagnosing the page. Include can also load related entities when the view genuinely needs the entity graph, but projection is often better for read-only lists.
Code Example
var rows = await db.Products
.AsNoTracking()
.Select(p => new ProductRowVm
{
Id = p.Id,
Name = p.Name,
Category = p.Category.Name
})
.ToListAsync(token);