10.11 — DTOs vs Entities and Mapping Approaches¶
← Roadmap · Section: 10. Web API Design and REST Prev: 10.10 CORS · Next: 10.12 Minimal APIs
Markers: 🔥 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A DTO (Data Transfer Object) is a type that exists purely to define what crosses the API boundary — separate from your EF Core entities.
- Returning entities leaks your schema, invites over-posting, and causes serialization cycles and lazy-loading queries mid-response.
- Use separate types for input and output. A request DTO and a response DTO are rarely the same shape.
- Mapping options: manual, Mapperly (source-generated), AutoMapper (reflection). Manual or Mapperly for new code.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| DTO | a plain class or record | A type whose only job is carrying data across a boundary. |
| Entity | a class | A type mapped to a database table by EF Core. |
| Request DTO / input model | a class | What the client sends. Shaped for input. |
| Response DTO | a class | What the client receives. Shaped for output. |
| Over-posting | a vulnerability | Model binding setting properties the client should not control. |
| Projection | a technique | Selecting straight into a DTO inside the query, so SQL returns only those columns. |
| AutoMapper | a NuGet package | Convention-based mapping via reflection. Now commercially licensed. |
| Mapperly | a NuGet package | Source-generated mapping. Compile-time, zero reflection. |
Select() projection |
a LINQ method | Where mapping becomes part of the SQL. |
| Anaemic model | a criticism | Objects with data and no behaviour. |
The concept¶
An entity is shaped for the database. A DTO is shaped for the client. They differ because those are different jobs.
// Shaped for storage: navigation properties, audit columns, internal flags
public class Order
{
public int Id { get; set; }
public string Reference { get; set; } = "";
public int CustomerId { get; set; }
public Customer Customer { get; set; } = null!; // navigation
public ICollection<OrderLine> Lines { get; set; } = [];
public decimal Total { get; set; }
public string Status { get; set; } = "";
public string? InternalNotes { get; set; } // ⚠️ staff-only
public decimal CostPrice { get; set; } // ⚠️ never show a customer
public DateTime CreatedUtc { get; set; }
public string CreatedBy { get; set; } = "";
public byte[] RowVersion { get; set; } = []; // concurrency token
}
// Shaped for the client: exactly what they need, nothing else
public sealed record OrderDto(
int Id,
string Reference,
string CustomerName,
IReadOnlyList<OrderLineDto> Lines,
decimal Total,
string Status,
DateTime CreatedUtc);
The four concrete reasons¶
1. Over-posting. Bind a request to the entity and model binding fills every settable property
from the request body. A client sends {"total": 0.01, "status": "Paid"} and the entity happily
takes it (11.10).
2. Leaking data. CostPrice and InternalNotes serialize by default. [JsonIgnore] works
until someone adds a new column and forgets. A DTO is opt-in; an entity is opt-out, and opt-out
fails quietly.
3. Serialization cycles and lazy loading. Order.Customer.Orders[0].Customer… is a cycle;
System.Text.Json throws on it. Worse, if lazy loading is on, serializing an entity fires database
queries while the response is being written — N+1 in the middle of the response, after your
DbContext timing looked fine (13.9).
4. Coupling your API to your schema. Rename a column and every client breaks. The DTO is the insulation layer that lets the database evolve independently (10.6).
The analogy¶
An entity is your personnel file — salary, notes, everything. The DTO is the name badge. You do not hand out the file because the badge would take five minutes to prepare.
How it works¶
Separate input and output DTOs¶
A common half-measure is one DTO for both directions. It rarely fits:
// What the client SENDS — no Id (server assigns), no Total (server computes)
public sealed record CreateOrderRequest
{
[Required, StringLength(50)]
public string Reference { get; init; } = "";
[Required, MinLength(1)]
public IReadOnlyList<CreateOrderLineRequest> Lines { get; init; } = [];
public string? DeliveryNote { get; init; }
}
// What the client RECEIVES — Id, Total, Status, all server-owned
public sealed record OrderDto(
int Id,
string Reference,
string CustomerName,
decimal Total,
string Status,
DateTime CreatedUtc);
⚠️ Fields the server owns must not be on the request type at all. Not ignored, not validated —
absent. If Total is not a property of CreateOrderRequest, no amount of creative posting can set
it. That is a structural guarantee rather than a rule someone has to remember.
⚠️ record with init accessors does not prevent over-posting. Model binding uses the
constructor or the init setters happily. The protection comes from the type not having the
property.
The projection point — where the performance actually is¶
// ⚠️ Loads every column of every order, plus the customer, then throws most away
var orders = await _db.Orders
.Include(o => o.Customer)
.Include(o => o.Lines)
.ToListAsync(ct);
return orders.Select(o => new OrderDto(...)).ToList();
// ✅ SELECTs only the columns the DTO needs. One query, one JOIN, no tracking.
var orders = await _db.Orders
.AsNoTracking()
.Select(o => new OrderDto(
o.Id,
o.Reference,
o.Customer.Name, // becomes a JOIN
o.Lines.Select(l => new OrderLineDto(l.ProductName, l.Quantity, l.Price)).ToList(),
o.Lines.Sum(l => l.Price * l.Quantity), // computed in SQL
o.Status,
o.CreatedUtc))
.ToListAsync(ct);
The second version never materialises an entity. The mapping is part of the SQL, so
InternalNotes and CostPrice are not merely hidden — they are never read from the database. On a
wide table that is a large difference in I/O.
⚠️ Include plus a later Select is the anti-pattern. Projecting makes Include redundant —
and worse, it still loads everything. Drop the Include when you project.
The mapping options¶
| Manual | Mapperly | AutoMapper | |
|---|---|---|---|
| How | You write it | Source generator | Reflection + config |
| Speed | ✅ Fastest | ✅ Same as manual | ⚠️ Slower |
| Errors surface | Compile time | ✅ Compile time | ⚠️ Runtime |
| Boilerplate | ⚠️ Most | ✅ Little | ✅ Least |
| Debuggable | ✅ Step into it | ✅ Generated code is readable | ⚠️ Opaque |
| Native AOT | ✅ | ✅ | ❌ |
| Licence | — | MIT | ⚠️ Commercial since v15 (2025) |
⚠️ AutoMapper went commercial in 2025. Versions from 15.0 require a paid licence for organisations above a revenue threshold. That is recent, it is a live topic in .NET teams, and knowing it signals you follow the ecosystem.
⚠️ The older criticism of AutoMapper stands regardless of licensing: a renamed property does
not break the build, it breaks at runtime — or silently maps null. AssertConfigurationIsValid()
in a test catches it, but that is a thing you must remember to do; a source generator makes it a
compile error you cannot skip.
Mapperly — the current recommendation for anything non-trivial:
[Mapper]
public partial class OrderMapper
{
// The generator writes the body. A missing or renamed property is a BUILD ERROR.
public partial OrderDto ToDto(Order order);
[MapProperty(nameof(Order.Customer.Name), nameof(OrderDto.CustomerName))]
public partial OrderDto ToDtoWithCustomer(Order order);
}
Manual — still right for a small number of DTOs, and the most explicit:
public static class OrderMappings
{
public static OrderDto ToDto(this Order order) => new(
order.Id,
order.Reference,
order.Customer.Name,
order.Lines.Select(l => l.ToDto()).ToList(),
order.Total,
order.Status,
order.CreatedUtc);
}
The deeper detail — the counter-argument¶
⚠️ DTOs are not free, and the honest answer acknowledges that.
- For a genuinely CRUD-shaped internal service, DTOs can be three near-identical types per entity.
- Every new field is edited in several places.
- Mapping code needs its own tests.
- It contributes to the "anaemic model" criticism (22.14).
Where the line sits:
| Situation | DTO? |
|---|---|
| Public or partner API | ✅ Always |
| Anything with sensitive columns | ✅ Always |
| Internal service, own team, CRUD | ⚠️ Defensible without |
| Prototype | ⚠️ Skip and mean it |
| Anything accepting input | ✅ Always — over-posting |
The one non-negotiable is input. You can argue about returning an entity from a read endpoint. Accepting one on a write endpoint is over-posting waiting to happen, and there is no version of that argument that wins.
Code¶
The read path, projecting in SQL:
public async Task<OrderDto?> GetAsync(int id, CancellationToken ct)
{
return await _db.Orders
.AsNoTracking() // read-only: skip change tracking
.Where(o => o.Id == id)
.Select(o => new OrderDto( // ← mapping happens IN the SQL
o.Id,
o.Reference,
o.Customer.Name, // JOIN, not lazy loading
o.Lines
.OrderBy(l => l.LineNumber)
.Select(l => new OrderLineDto(l.ProductName, l.Quantity, l.UnitPrice))
.ToList(),
o.Lines.Sum(l => l.Quantity * l.UnitPrice), // SUM in SQL
o.Status,
o.CreatedUtc))
.FirstOrDefaultAsync(ct);
// CostPrice and InternalNotes are never selected, so they cannot leak.
}
The write path, where the DTO is a security boundary:
public async Task<OrderDto> CreateAsync(CreateOrderRequest request, CancellationToken ct)
{
// Every server-owned field is set HERE, from server state — never from the request.
// CreateOrderRequest has no Total, Status, CreatedBy or Id property to bind at all.
var order = new Order
{
Reference = request.Reference,
CustomerId = _currentUser.CustomerId, // from the token, not the body
Status = OrderStatus.Pending, // server decides
CreatedUtc = _clock.UtcNow,
CreatedBy = _currentUser.UserId,
Lines = request.Lines.Select(l => new OrderLine
{
ProductId = l.ProductId,
Quantity = l.Quantity,
// ⚠️ Price comes from the catalogue, NEVER from the request.
// Trusting a client-supplied price is how you sell things for a penny.
UnitPrice = _catalogue.GetPrice(l.ProductId)
}).ToList()
};
order.Total = order.Lines.Sum(l => l.Quantity * l.UnitPrice);
_db.Orders.Add(order);
await _db.SaveChangesAsync(ct);
return order.ToDto();
}
That UnitPrice line is the whole argument in one statement. A client-supplied price on a request
DTO is still a client-supplied price — the DTO protects you from binding surprises, not from
trusting the wrong field. The two defences are separate.
Update with a DTO that carries only editable fields:
public sealed record UpdateOrderRequest
{
[Required, StringLength(500)]
public string DeliveryNote { get; init; } = "";
[Required]
public AddressDto DeliveryAddress { get; init; } = null!;
// Concurrency token — round-tripped so a stale update is detected
[Required]
public string RowVersion { get; init; } = "";
}
public async Task<UpdateResult> UpdateAsync(
int id, UpdateOrderRequest request, CancellationToken ct)
{
var order = await _db.Orders.FindAsync([id], ct);
if (order is null) return UpdateResult.NotFound;
// ⚠️ Explicit assignment of the three editable fields. Nothing else can change,
// because nothing else is on the request type.
order.DeliveryNote = request.DeliveryNote;
order.DeliveryAddress = request.DeliveryAddress.ToValueObject();
_db.Entry(order).Property(o => o.RowVersion)
.OriginalValue = Convert.FromBase64String(request.RowVersion);
try
{
await _db.SaveChangesAsync(ct);
return UpdateResult.Success;
}
catch (DbUpdateConcurrencyException)
{
return UpdateResult.Conflict; // → the controller turns this into a 409
}
}
Interview questions¶
Q: Why not return EF entities from an API?
Four reasons. Over-posting, if the same type is used for input — model binding sets every settable
property, so a client can write Status or Total. Data leakage, because serialization is opt-out:
a new column on the entity appears in the response by default and nobody notices. Serialization
problems — navigation properties create cycles, and with lazy loading enabled the serializer fires
database queries while the response is being written, so you get N+1 after the point where you were
measuring. And coupling: the entity is your database schema, so renaming a column breaks every
client. The DTO is where the API contract lives, separately from storage.
Q: Should input and output DTOs be the same type?
Usually not, because they carry different fields. The response has Id, Total and Status, all
server-owned; the request should not have them at all. That absence is the point — a property that
does not exist on the request type cannot be bound, whatever the client sends, which is a
structural guarantee rather than a rule someone has to remember to enforce. Sharing one type
usually means adding [JsonIgnore] or validation to suppress fields, which is the weaker version of
the same idea.
Q: Manual mapping, AutoMapper or something else?
Manual for a handful of DTOs, and Mapperly once it gets tedious — it is a source generator, so mapping code is written at compile time and a renamed or missing property is a build error rather than a runtime surprise, with no reflection cost and Native AOT support. I would not start a new project on AutoMapper: the long-standing objection is that misconfiguration surfaces at runtime unless you remember to assert the configuration in a test, and since version 15 in 2025 it also requires a commercial licence above a revenue threshold. Existing AutoMapper code is fine; it is just not where I would start.
Q: Is there a case against DTOs?
Yes, and it is worth being honest about. For a CRUD-shaped internal service they can be three near-identical types per entity, every new field is edited in several places, and the mapping needs its own tests. For an internal API owned by one team I would not argue hard against returning entities from read endpoints. The part I would not concede is input: accepting an entity on a write endpoint is over-posting, and there is no version of that trade that comes out well.
Traps ⚠️¶
- Binding a request to an entity — over-posting.
Includefollowed bySelectloads everything and then discards it.- Projecting after
ToListAsync()does the mapping in memory, not SQL. - Serializing entities with lazy loading fires queries mid-response.
- Navigation properties cause serialization cycles and throw.
[JsonIgnore]as the only defence — opt-out fails when a column is added.recordwithinitdoes not stop model binding. Omit the property instead.- Trusting a client-supplied price even on a proper DTO.
- AutoMapper misconfiguration is a runtime failure unless asserted in a test.
- AutoMapper 15+ requires a commercial licence.
- One DTO for input and output forces server-owned fields onto the request.
- Forgetting
AsNoTracking()on read paths tracks entities you never modify.
Related¶
- 10.1 REST principles — representations vs storage
- 10.5 Content negotiation and JSON — serializing the DTO
- 10.6 API versioning — DTOs as the versioned contract
- 10.9 OpenAPI — DTOs become schemas
- 11.10 Over-posting — the vulnerability in full
- 13.9 N+1 — why serializing entities hurts
- 13.8 Loading strategies — projection vs
Include - 9.8 ViewModels — the same argument for views
- 22.14 Anti-patterns — the anaemic model criticism