ASP.NET Core MVC Interview Question #184

How would you optimize an MVC dashboard that executes many database queries?

Senior Practical MVC Scenarios & Production Architecture Senior Advanced

Quick Interview Answer

Start by measuring query count and duration. Consolidate compatible aggregations, project only required values, use AsNoTracking for read-only work, execute independent operations carefully, and cache results only when their freshness requirements allow it.

Detailed Explanation

Start by measuring query count and duration. Consolidate compatible aggregations, project only required values, use AsNoTracking for read-only work, execute independent operations carefully, and cache results only when their freshness requirements allow it.

Avoid loading full entity collections merely to count or aggregate them in memory. Push filtering and aggregation to the database whenever practical.

Code Example

var stats = await db.Orders
    .AsNoTracking()
    .GroupBy(_ => 1)
    .Select(g => new DashboardVm
    {
        Total = g.Count(),
        Open = g.Count(x => x.Status == "Open"),
        Revenue = g.Sum(x => x.Total)
    })
    .SingleAsync(token);