Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 52 ยท Models, Validation and Serialization

DTOs, Records and Mapping

Why APIs should not expose entities: use record DTOs, write simple mapping methods, project queries, and evolve response shapes without breaking clients.

Your application has entities: the classes that mirror your database tables or your domain, with every column and every internal flag. It is tempting to take one of those straight from a query and return it from an endpoint, and to accept it straight from a request body. Resist the temptation. An entity is shaped for storage and business logic; an API message is shaped for a client. Treating them as the same thing creates security holes, accidental contracts and painful changes.

The cure is a data transfer object (DTO): a small, dumb type that describes exactly what goes over the wire. In this lesson you will see what goes wrong without DTOs, how C# records make DTOs nearly free, how to map by hand, why queries should project straight into DTOs, and how separate shapes let your API evolve.

What goes wrong when you expose entities

Three problems show up sooner or later:

  1. Leaking. The entity has a PasswordHash, an IsAdmin flag or an internal note. The serializer writes every public property, so it all ends up in the response.
  2. Mass assignment (over-posting). If an endpoint binds a request body to the entity, a client can set any property: {"name":"Mallory","isAdmin":true}. Nothing in your code asked for that field, yet it was assigned.
  3. Frozen design. Once clients depend on your entity's JSON, renaming a column or splitting a table breaks them. The database schema has quietly become your public contract.
flowchart LR
    A["Client JSON"] --> B["Request DTO<br/>only fields you accept"]
    B --> C["Mapping"]
    C --> D["Entity<br/>domain + storage"]
    D --> E["Mapping"]
    E --> F["Response DTO<br/>only fields you promise"]
    F --> G["Client JSON"]

DTOs sit at the edge: the entity never meets the network.

C# Leaking and over-posting, then the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The "bad" GET returns the password hash and admin flag, and the "bad" POST let an attacker create an administrator. The "good" endpoints use RegisterRequest (which has no IsAdmin property to set) and UserResponse (which has no hash to leak). Notice that the DTO approach needed no extra libraries: a record and one mapping method.

[JsonIgnore] on the entity is not a substitute. It works until someone adds the next sensitive property and forgets the attribute. A separate DTO is an allow-list: only what you list can leave or enter.

Records make good DTOs

A positional record is the natural DTO. In a single line you get a constructor, read-only properties, value equality, a readable ToString() and non-destructive copying with with. They are also immutable by default, so nobody modifies a message halfway through your pipeline. If you are new to them, see Records in C#.

C#
public record ProductSummary(int Id, string Name, decimal Price);

// Nested, optional and computed pieces are just more records and properties
public record OrderDetail(int Id, string Customer, IReadOnlyList<LineDto> Lines)
{
    public decimal Total => Lines.Sum(l => l.Quantity * l.UnitPrice);
}

A few conventions keep DTOs pleasant:

  • Name them by purpose: CreateProductRequest, UpdateProductRequest, ProductSummary, ProductDetail. A separate request type per operation is normal, because create, update and patch accept different fields.
  • Put validation attributes on request types, not on entities (Model Validation).
  • Keep DTOs free of behavior beyond trivial computed values. They carry data.
  • Use required or constructor parameters for mandatory fields, and ? for optional ones.

Mapping by hand

Mapping is the code that copies data between an entity and a DTO. The simplest approach is a static method per direction, usually an extension method, as in the example above. It is explicit, debuggable (click into it and set a breakpoint) and fast, and the compiler tells you when a new property needs attention. Libraries that map by convention exist, but for most APIs a few hundred lines of plain mapping code are easier to maintain than a configuration whose failures show up at runtime.

Map in one place: either next to the DTO or in a Mapping class per feature, never inline in every handler.

Projection: map in the query, not after it

When data comes from a database, there is a second reason to love DTOs. If you load full entities and then map, the database sends every column of every row, and your code throws most of it away. If instead you project with Select, an ORM such as EF Core translates the expression into a query that fetches only the columns the DTO needs.

C#
// Read-only sketch: EF Core turns the Select into "SELECT Id, Name, Price FROM Products"
List<ProductSummary> summaries = await db.Products
    .Where(p => p.Stock > 0)
    .Select(p => new ProductSummary(p.Id, p.Name, p.Price))
    .ToListAsync();

The key is that Select receives an expression tree (data describing the code), not a compiled delegate, when called on an IQueryable. The data-access lessons come back to this (Entity Framework Core Overview). Here we can show the same idea with LINQ over memory: a projection is both runnable code and an inspectable expression.

C# Mapping methods, nested DTOs and a projection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The supplier note is a column the client must never see, and it never appears: not in the list, not in the order detail. The order mapping also shapes data for the reader by joining names and prices and computing the total, which is something an entity cannot do for you without becoming a grab bag of display properties.

Shapes that can evolve

A DTO is a contract, and contracts change. Because the entity and the DTO are separate, you can change the database without touching clients, and you can add a new DTO next to the old one when the contract must change.

Safe, additive changes include adding a response field, adding an optional request field, and adding a new endpoint. Existing clients simply ignore what they do not know. Breaking changes are removing or renaming a field, changing its type, or making an optional field required. When you need one, publish the new shape as a new version and keep the old one working for a while.

C# Two versions of one resource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line is the lesson in miniature: an old client reading the v2 payload still finds its id, but name is gone. That would have been a safe change only if name had stayed. Adding fields is free; removing or renaming them is a new version. The lesson on OpenAPI and versioning covers how to expose versions cleanly.

Practical advice

  • One DTO per purpose. Do not reuse a response type as a request type; the fields you return and the fields you accept differ.
  • Make mapping the only place that knows both shapes. Handlers should call ToResponse(), not copy fields inline.
  • Project in queries for list endpoints and keep entity loading for places that actually change data.
  • Do not map in the controller or endpoint if a service already returns a DTO-shaped result for you; avoid mapping twice.
  • Do not nest entities inside DTOs. Every nested type you return is another contract; map them too.
  • Test mapping. A tiny unit test that maps a fully populated entity and checks each field catches silent drops.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client posts {"name":"x","isAdmin":true} to an endpoint that takes an entity with an IsAdmin property. What is this problem called?

    Binding to an entity lets a client set any public property, including ones you never intended to accept. Request DTOs list exactly which fields are allowed.
  2. 2. Why is [JsonIgnore] on an entity weaker than a response DTO?

    A DTO is an allow-list. Only properties you declare leave the server, so forgetting about a new entity property cannot leak it.
  3. 3. What advantage does projecting with Select into a DTO have when the data comes from a database through an ORM?

    On an IQueryable the Select is an expression tree that the provider can translate into a query selecting only the needed columns, so less data travels from the database.
  4. 4. Which change to a response DTO is generally safe for existing clients?

    Clients that deserialize leniently ignore fields they do not know. Renames, type changes and removals break them and call for a new version.
  5. 5. Where should the code that copies data between an entity and a DTO live?

    Keeping mapping in one place avoids duplicated field-copying and gives you a single spot to change and test.

Summary

  • Entities describe storage and domain; DTOs describe messages. Keeping them apart prevents leaks, over-posting and an accidental public schema.
  • Records are ideal DTOs: concise, immutable, with value equality and with copies.
  • Map by hand with extension methods or a per-feature mapper; it is explicit, debuggable and checked by the compiler.
  • Project with Select in queries so only the needed columns are loaded.
  • Add fields freely, but treat removals, renames and type changes as a new version of the shape.

Next: Controllers and Actions