ASP.NET Core MVC Interview Question #147

Why should ViewModels be projected at the database query level when practical?

Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced

Quick Interview Answer

Projecting directly into a list or page ViewModel can reduce the amount of data retrieved and avoid materializing complete entity graphs that the UI does not need. With EF Core, a Select projection can often be translated into a focused SQL query.

Detailed Explanation

Projecting directly into a list or page ViewModel can reduce the amount of data retrieved and avoid materializing complete entity graphs that the UI does not need. With EF Core, a Select projection can often be translated into a focused SQL query.

Projection is especially useful for read-only listing pages. It also reduces accidental coupling between Razor views and persistence entities.

Code Example

var model = await db.Products
    .AsNoTracking()
    .Where(p => p.IsPublished)
    .Select(p => new ProductListItem
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync(token);