Skip to content

9.8 — ViewModels vs Entities, and Strongly-Typed Views

← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.7 Razor Pages · Next: 9.9 Blazor overview

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

A ViewModel is a class shaped for one specific view — exactly what that page needs, nothing more.

  • Passing an EF entity to a view causes three real problems: over-posting, lazy-loading queries during rendering, and logic leaking into the view.
  • A ViewModel is where presentation decisions live — CanCancel, StatusCssClass, formatted totals.
  • @model makes the view strongly typed, so IntelliSense works and typos are compile errors.

Definitions

Term What it is What it means
ViewModel a class shaped for one view Holds exactly what that page renders. Has no persistence concerns.
Entity a domain / EF class Maps to a database table. Has navigation properties and identity.
DTO a class shaped for an API contract The API equivalent of a ViewModel. See 10.11.
Input model a class shaped for a form post What model binding populates. Only the fields the user may set.
@model a Razor directive Declares the type of Model, making the view strongly typed.
Strongly-typed view a view with @model IntelliSense and compile-time checking on Model.
Over-posting a vulnerability A user setting a property you did not intend to expose. See 11.10.
Projection a query technique Selecting only the columns you need — Select(o => new Dto {...}).
Mapping converting between shapes Manual, or with a library like Mapperly or AutoMapper.

The concept

Why not just pass the entity?

It is the obvious shortcut, and it looks harmless:

// ✗ The shortcut
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
    var order = await _db.Orders.FindAsync([id], ct);
    return View(order);                              // the EF entity, straight to the view
}

Three problems follow, and only the first is obvious.

1. Over-posting on the way back in. If the same entity type is used for a form post, model binding populates every settable property from the request. A user adding Status=Shipped or TotalPaid=0 to the form data sets it — no error, no warning (11.10).

2. Lazy-loading queries during rendering. If the view touches order.Customer.Name and Customer was not loaded, lazy loading fires a query while the page is rendering. Do that in a loop and you have an N+1 problem inside your view (13.9). With the DbContext already disposed, you instead get an ObjectDisposedException.

3. Logic leaking into the view. The view has an entity, so it starts asking the entity questions:

@* ✗ Business rules in a template — untestable *@
@if (Model.Status == OrderStatus.Pending &&
     Model.CreatedAt > DateTime.UtcNow.AddDays(-30))
{
    <button>Cancel</button>
}

A ViewModel fixes all three by being a different class, shaped for the page.

A picture: a menu versus the kitchen's stock list. The stock list has supplier codes, quantities and costs. The menu has dish names, descriptions and prices. Handing customers the stock list would work, and it would tell them things they should not see and nothing they actually want.


How it works

The simple version

public class OrderDetailsViewModel
{
    public Guid Id { get; init; }
    public string Reference { get; init; } = "";
    public string CustomerName { get; init; } = "";
    public DateTimeOffset CreatedAt { get; init; }
    public decimal Total { get; init; }

    // Presentation DECISIONS, made before rendering
    public bool CanCancel { get; init; }
    public string StatusText { get; init; } = "";
    public string StatusCssClass { get; init; } = "";

    public IReadOnlyList<OrderLineViewModel> Lines { get; init; } = [];

    public static OrderDetailsViewModel From(Order order, DateTimeOffset now) => new()
    {
        Id           = order.Id,
        Reference    = order.Reference,
        CustomerName = order.Customer.Name,
        CreatedAt    = order.CreatedAt,
        Total        = order.Total,

        CanCancel      = order.CanBeCancelled(now),        // the RULE lives on the entity
        StatusText     = order.Status.ToDisplayString(),
        StatusCssClass = order.Status switch
        {
            OrderStatus.Shipped   => "badge bg-success",
            OrderStatus.Cancelled => "badge bg-danger",
            _                     => "badge bg-secondary"
        },

        Lines = order.Lines.Select(OrderLineViewModel.From).ToList()
    };
}
@model OrderDetailsViewModel

<h1>Order @Model.Reference <span class="@Model.StatusCssClass">@Model.StatusText</span></h1>

@if (Model.CanCancel)
{
    <form asp-action="Cancel" asp-route-id="@Model.Id" method="post">
        <button type="submit" class="btn btn-danger">Cancel this order</button>
    </form>
}

Note where the decision was made. CanCancel was computed by asking the entity — the rule still lives with the domain object (9.1) — but the result is a plain bool on the ViewModel. The view asks a question; it does not evaluate a rule.

That is what makes the rule testable: order.CanBeCancelled(now) is a unit test, and a @if in a template is not.

⚠️ Separate models for reading and writing

The other common mistake is using one ViewModel for both display and form posts:

// ✗ One class doing both jobs
public class OrderViewModel
{
    public Guid Id { get; set; }
    public string CustomerName { get; set; } = "";
    public decimal Total { get; set; }              // ⚠️ user could post this
    public OrderStatus Status { get; set; }         // ⚠️ and this
}

Anything with a setter can be posted. Split them:

// ✓ Display — init-only, so nothing is bindable
public class OrderDetailsViewModel
{
    public Guid Id { get; init; }
    public decimal Total { get; init; }
    public bool CanCancel { get; init; }
}

// ✓ Input — ONLY the fields a user may set
public class EditOrderInput
{
    [Required, StringLength(100)]
    public string CustomerName { get; set; } = "";

    [Required, StringLength(200)]
    public string ShippingAddress { get; set; } = "";
    // No Total. No Status. No Id — that comes from the route.
}

An input model is a security boundary, not just tidiness. The properties it does not have cannot be set, whatever the request contains.

⚠️ init setters still bind. The binder can set them during construction, so init alone does not prevent over-posting — a separate input model does (11.10).

How it actually works — projecting in the query

The best version does not load the entity at all. Project directly:

public async Task<OrderDetailsViewModel?> GetDetailsAsync(Guid id, CancellationToken ct)
{
    return await _db.Orders
        .AsNoTracking()
        .Where(o => o.Id == id)
        .Select(o => new OrderDetailsViewModel
        {
            Id           = o.Id,
            Reference    = o.Reference,
            CustomerName = o.Customer.Name,          // becomes a JOIN, not lazy loading
            CreatedAt    = o.CreatedAt,
            Total        = o.Lines.Sum(l => l.Price * l.Quantity),
            Lines        = o.Lines.Select(l => new OrderLineViewModel
            {
                ProductName = l.Product.Name,
                Quantity    = l.Quantity,
                LineTotal   = l.Price * l.Quantity
            }).ToList()
        })
        .FirstOrDefaultAsync(ct);
}

Three benefits over loading and mapping:

Only the needed columns are selected. EF generates a SELECT naming them, rather than SELECT * on every joined table.

No lazy loading is possible, because no entity is tracked (13.8).

No change tracking overhead — AsNoTracking plus a projection means nothing to track (13.7).

⚠️ The catch: computed properties do not translate. CanCancel = o.CanBeCancelled(now) inside a Select fails, because EF cannot turn a C# method into SQL (2.7). Either express the rule as translatable LINQ, or compute it after materialising:

var vm = await query.FirstOrDefaultAsync(ct);
if (vm is not null)
    vm = vm with { CanCancel = /* computed here, in memory */ };

A practical compromise: project the data, then compute presentation properties in the mapping step after the query.

Mapping options

Manual — a static factory or extension method:

public static OrderDetailsViewModel From(Order order, DateTimeOffset now) => new() { ... };

Explicit and greppable, with no dependency. This is the right default.

Mapperly — a source generator producing the mapping code at compile time:

[Mapper]
public partial class OrderMapper
{
    public partial OrderDetailsViewModel ToViewModel(Order order);
}

Compile-time, so it is AOT-friendly and a missing property is an error rather than a runtime surprise (3.2).

AutoMapper — reflection-based, configured by convention.

⚠️ AutoMapper's cost is that mapping mistakes become runtime failures, and the mapping is invisible at the call site — you cannot see what a property maps from without opening the profile. For a large codebase with hundreds of near-identical mappings it earns its place; for a handful, manual mapping is clearer and has no magic.

Strongly-typed views

@model is what makes the view checkable:

@model OrderDetailsViewModel        @* ✓ IntelliSense, compile-time checking *@

<h1>@Model.Referenc</h1>           @* ✗ compile error — caught at build *@

Without it, Model is dynamic and a typo silently renders nothing (9.6 — the same problem as ViewBag).

⚠️ Razor views are compiled, so @model errors surface at build time in modern .NET — <RazorCompileOnBuild> is on by default. That is a genuine safety net, and it is why untyped ViewData is worse than it looks: those errors never surface at all.


Code

The full slice, showing where each decision belongs:

// ── Domain: the rule lives here ──
public class Order
{
    public OrderStatus Status { get; private set; }
    public DateTimeOffset CreatedAt { get; init; }

    public bool CanBeCancelled(DateTimeOffset now) =>
        Status is OrderStatus.Pending or OrderStatus.Confirmed &&
        CreatedAt > now.AddDays(-30);
}
// ── Service: projects to a ViewModel ──
public class OrderQueryService(AppDbContext db, TimeProvider time)
{
    public async Task<OrderDetailsViewModel?> GetDetailsAsync(Guid id, CancellationToken ct)
    {
        var order = await db.Orders
            .AsNoTracking()
            .Include(o => o.Customer)
            .Include(o => o.Lines).ThenInclude(l => l.Product)
            .FirstOrDefaultAsync(o => o.Id == id, ct);

        return order is null ? null : OrderDetailsViewModel.From(order, time.GetUtcNow());
    }
}
// ── Controller: thin ──
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
    var vm = await _query.GetDetailsAsync(id, ct);
    return vm is null ? NotFound() : View(vm);
}
@* ── View: rendering only ── *@
@model OrderDetailsViewModel

<h1>Order @Model.Reference</h1>
<span class="@Model.StatusCssClass">@Model.StatusText</span>

<table class="table">
@foreach (var line in Model.Lines)
{
    <tr>
        <td>@line.ProductName</td>
        <td>@line.Quantity</td>
        <td>@line.LineTotal.ToString("C")</td>
    </tr>
}
</table>

@if (Model.CanCancel)
{
    <form asp-action="Cancel" asp-route-id="@Model.Id" method="post">
        <button type="submit">Cancel</button>
    </form>
}

And the edit form, with a separate input model

[HttpGet("{id:guid}/edit")]
public async Task<IActionResult> Edit(Guid id, CancellationToken ct)
{
    var order = await _orders.GetAsync(id, ct);
    if (order is null) return NotFound();

    return View(new EditOrderInput
    {
        CustomerName    = order.Customer.Name,
        ShippingAddress = order.ShippingAddress
    });
}

[HttpPost("{id:guid}/edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, EditOrderInput input, CancellationToken ct)
{
    if (!ModelState.IsValid) return View(input);

    // 'id' comes from the ROUTE, not the form — the user cannot change which
    // order they are editing by tampering with a hidden field
    await _orders.UpdateAsync(id, input.CustomerName, input.ShippingAddress, ct);

    TempData["Success"] = "Order updated.";
    return RedirectToAction(nameof(Details), new { id });
}

⚠️ Taking id from the route rather than the input model matters. A hidden Id field in the form can be edited in the browser, so binding it from the body lets a user edit an order that is not theirs — unless you re-check ownership. The route value plus an authorization check is the safer shape (16.6).


Interview questions

Q: Why not pass an EF entity straight to a view?

Three reasons. Over-posting — if the same type is used for a form post, model binding sets every settable property from the request, so a user can add a field like Status and change it. Lazy loading — a view touching an unloaded navigation property fires a query during rendering, which becomes N+1 inside a loop, or throws if the DbContext has already been disposed. And logic leaking into the view, because once the view has an entity it starts evaluating business rules in the template, which cannot be unit tested.

Q: What should a ViewModel contain?

Exactly what that page renders, with presentation decisions already made. So instead of the view checking a status and a date to decide whether to show a cancel button, the ViewModel has a CanCancel bool — computed by asking the domain object, so the rule still lives with the entity and stays testable, but the result reaches the view as a plain value. The same applies to a CSS class chosen from a status, or a formatted total. The view asks questions; it does not evaluate rules.

Q: Should you use the same class for display and for form posts?

No. Anything with a settable property can be posted, so a display model doubling as an input model exposes every field. I would use an init-only ViewModel for display and a separate input model containing only the fields a user may legitimately set — no totals, no status, no ID. The input model is a security boundary rather than just tidiness: the properties it does not have cannot be set regardless of what the request contains. Worth noting that init setters still bind, so immutability alone does not prevent over-posting.

Q: What is the best way to build a ViewModel from the database?

Project directly in the query with Select, rather than loading the entity and mapping afterwards. EF then generates SQL selecting only the columns you need, joins rather than lazy loads, and there is nothing to track. The catch is that computed properties do not translate — a C# method call inside a Select cannot become SQL — so anything like CanCancel has to be expressed as translatable LINQ or computed after materialising. In practice I project the data and compute the presentation properties in the mapping step.


Traps ⚠️

  • Passing an entity to a view risks over-posting, lazy-loading queries during rendering, and logic in templates.
  • One class for display and input exposes every settable property.
  • init setters still bind. Immutability does not prevent over-posting; a separate input model does.
  • Computed properties do not translate in a Select projection. EF cannot turn a method call into SQL.
  • Binding an Id from the form lets a user change which record they are editing.
  • Without @model the view is dynamic, so typos render nothing rather than failing.
  • AutoMapper turns mapping mistakes into runtime failures and hides what maps from what.
  • Lazy loading after the DbContext is disposed throws during rendering, not in the controller.


Sources