DTO pattern: Fowler's origin (batching data across a process boundary), a data-only contract with no behaviour, why exposing EF Core entities in APIs is risky (over-posting/mass assignment, leaking sensitive fields under the Privacy Act, schema changes breaking clients, JSON object cycles), separate request and response DTOs, records as immutable DTOs, and when not to add DTOs (inside one layer).
A DTO is a data-only object that carries data across a boundary, like an HTTP API, a message or another service. Fowler described it as a way to batch several values into one remote call. It has no behaviour.
In ASP.NET Core you shouldn't bind or return EF Core entities directly:
IsAdmin: true and the model binder sets it.PasswordHash or a date of birth ends up in responses.Use separate request and response DTOs, written as positional records, which are concise and immutable. Keep DTOs at boundaries. The trade-off is a little mapping code in exchange for a stable, safe API contract.
"A DTO is an object whose only job is to carry data across a boundary. Fowler described it for remote calls: instead of making ten calls to get a customer's name, address and so on, you send one object with all of it. Today the boundary is usually an HTTP API or a message, and the DTO is the contract: just properties, no business logic.
The reason it matters in ASP.NET Core is what happens when you skip it and use the EF Core entity directly. If an endpoint binds a
Userentity on POST, the client can include"isAdmin": trueor"balance": 1000000and the model binder happily sets it. That's over-posting, or mass assignment. If an endpoint returns the entity, every property goes out, includingPasswordHash, internal flags, or a date of birth that we're obliged to protect under the Privacy Act. The API contract also becomes the database schema: rename a column and a mobile app breaks. And if the entity has navigation properties,Order.Customer.Orders..., System.Text.Json throws 'A possible object cycle was detected'. People reach forReferenceHandler.IgnoreCycles, but that only hides the fact that we're serialising an object graph rather than a contract.So I write a request DTO per operation, like
CreateUserRequest(string Email, string DisplayName), which can only carry what the client is allowed to set, and a response DTO likeUserResponse(Guid Id, string DisplayName). Positional records are ideal: one line, immutable, value equality, and System.Text.Json and minimal APIs handle them well. The mistake I see in the other direction is adding DTOs between every internal layer, mapping the same shape three times inside one process. DTOs belong at boundaries; inside a layer, pass domain objects."
| EF Core entity | DTO | |
|---|---|---|
| Purpose | Persist and enforce domain rules | Carry data across a boundary |
| Behaviour | Methods, invariants | None |
| Shape | Matches the domain/table | Matches one operation |
| Changes when | Schema or domain changes | The API contract changes (versioned) |
| Safe to bind/return | No | Yes |
| Problem | Example | DTO fix |
|---|---|---|
| Over-posting | Client sets IsAdmin = true |
Request DTO has no IsAdmin |
| Leaking data | PasswordHash, DOB in response |
Response DTO lists allowed fields only |
| Breaking clients | Column renamed | DTO stays stable; mapping changes |
| JSON cycles | Order.Customer.Orders |
Flat DTO without back-references |
| Lazy loading surprises | Serialiser triggers N queries | DTO built from a projection |
A user-profile endpoint returned the User entity, and a later migration added a MedicareNumber column. It appeared in API responses for nine days before a penetration test found it, which meant a privacy incident assessment. Switching to a UserProfileResponse record with five explicit fields made new columns invisible to clients by default.
Checks whether the candidate understands the DTO as a boundary contract and can name the concrete risks of exposing entities.
Green flags
Red flags
IgnoreCycles as the fix.Fowler's PoEAA (2002) introduced the DTO to reduce the number of remote calls: fine-grained object interfaces are expensive across a network, so you assemble a coarse-grained, serialisable object for the trip. The idea has since broadened to "the contract shape at any boundary".
Client JSON ---> CreateUserRequest (DTO) ---> handler maps ---> User (entity) ---> DbContext
Client JSON <--- UserResponse (DTO) <--- projection <--- Users table
Model binding sets every public settable property it finds in the request body. With an entity, that includes properties the client must never control. [Bind] attributes and "ignore these fields" lists are fragile because a new property is bindable by default. A request DTO is safe by construction: if the property doesn't exist, it can't be set.
System.Text.Json follows references. Order -> Customer -> Orders -> Order... either exceeds MaxDepth (64 by default) or is detected as a cycle, and throws JsonException. ReferenceHandler.Preserve emits $id/$ref metadata clients must understand; IgnoreCycles writes null for repeated references. Both are workarounds for serialising a graph instead of a contract.
public sealed record UserResponse(Guid Id, string DisplayName, string Email);
init-only), equality, ToString and deconstruction.Assert.Equal(expected, actual)).Record structs work too, but class records are the usual choice for API DTOs.
One DTO for both directions brings back the over-posting problem (Id and CreatedAt become bindable). Separate them, and for updates consider operation-specific DTOs (ChangeEmailRequest) rather than one giant UpdateUserRequest.
User entity in a minimal API POST and send "isAdmin": true; check the saved row.Order with Customer.Orders loaded and read the JsonException.Assert.Equal.An endpoint that binds and returns an entity, then the same endpoint with request and response DTOs.
namespace Accounts;
public sealed class User
{
public Guid Id { get; set; } = Guid.CreateVersion7();
public required string Email { get; set; }
public required string DisplayName { get; set; }
public string PasswordHash { get; set; } = "";
public DateOnly DateOfBirth { get; set; } // personal information: never in a response by accident
public bool IsAdmin { get; set; }
public List<Order> Orders { get; set; } = []; // navigation: causes JSON cycles
}
public sealed class Order
{
public Guid Id { get; set; }
public User? User { get; set; }
}
// BEFORE (don't): over-posting and data leaks
// app.MapPost("/users", async (User user, AppDbContext db, CancellationToken ct) =>
// {
// db.Users.Add(user); // client can send "isAdmin": true
// await db.SaveChangesAsync(ct);
// return Results.Ok(user); // PasswordHash and DateOfBirth go back out
// });
namespace Accounts;
using Microsoft.EntityFrameworkCore;
// Contracts: only what each operation needs
public sealed record CreateUserRequest(string Email, string DisplayName);
public sealed record UserResponse(Guid Id, string Email, string DisplayName);
public static class UserEndpoints
{
public static void MapUserEndpoints(this IEndpointRouteBuilder app)
{
app.MapPost("/users", async (CreateUserRequest request, AppDbContext db, CancellationToken ct) =>
{
var user = new User { Email = request.Email, DisplayName = request.DisplayName }; // IsAdmin can't be posted
db.Users.Add(user);
await db.SaveChangesAsync(ct);
return Results.Created($"/users/{user.Id}", new UserResponse(user.Id, user.Email, user.DisplayName));
});
app.MapGet("/users/{id:guid}", async (Guid id, AppDbContext db, CancellationToken ct) =>
await db.Users
.Where(u => u.Id == id)
.Select(u => new UserResponse(u.Id, u.Email, u.DisplayName)) // projection: no cycles, no extra columns
.SingleOrDefaultAsync(ct) is { } response
? Results.Ok(response)
: Results.NotFound());
}
}
IsAdmin or Balance (over-posting). Instead: Bind a request DTO that only contains settable fields.ReferenceHandler.IgnoreCycles. Why it is wrong: It hides that you're serialising an object graph, and clients get confusing nulls. Instead: Return flat DTOs without back-references.Id and CreatedAt become bindable. Instead: Separate request and response types.[Bind] or ignore lists on entities instead of DTOs. Why it is wrong: New properties are bindable by default, so it fails open. Instead: DTOs are safe by construction.The DTO is the cheapest security control in an API: if a property isn't on the request record it can't be over-posted, and if it isn't on the response record it can't leak. I'd rather write a few lines of mapping than rely on [JsonIgnore] or bind lists that fail open the day someone adds a column. The cost is real but small, and I keep it small by projecting response DTOs straight from the query and keeping DTOs at boundaries only.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Expose entities | Throwaway prototypes only | Over-posting, leaks, schema coupling | Anything with users or personal data |
[JsonIgnore] / [Bind] on entities |
Never as the main control | Fails open for new properties | Public or customer-facing APIs |
| Request + response records | Every API boundary | Mapping code (or a generator) | Between internal layers in one process |
| Versioned DTOs (v1/v2) | Public APIs with external clients | Parallel contracts to maintain | Internal APIs you deploy together |
I measure it with contract tests (snapshot the OpenAPI document and fail the build on unexpected changes) and by checking that responses contain no fields classified as personal information under APP 11 unless the endpoint needs them.
A domain model represents business concepts with behaviour and invariants (an Order that can be paid, cancelled, and refuses invalid changes). A DTO (data transfer object) is a flat, behaviour-free contract for moving data across a boundary: an HTTP request or response, a message, a query result. Keep them separate so that the API contract and the domain can change independently, so clients cannot over-post fields they must not set (IsAdmin, Status), and so internal data does not leak in responses. Map with explicit code, source-generated mappers (Mapperly) or EF Core projections straight to DTOs for reads. Sharing one type is acceptable only for simple CRUD with no rules, and even then be careful at public boundaries.
Prefer immutable types for values, messages, configuration, cache entries and anything shared across threads: an object that cannot change is automatically thread-safe, safe to cache and share, safe as a dictionary key, and easier to reason about. C# gives you readonly fields, init and get-only properties, records with with, readonly struct, ImmutableArray<T>/ImmutableList<T> and FrozenDictionary/FrozenSet for read-mostly data. Remember that read-only is not immutable: IReadOnlyList<T> over a List<T> can still change underneath. Keep mutability where it is natural and contained: entities whose state changes through methods that guard invariants, builders, and hot loops where allocating new objects would cost too much.
The Mapper pattern keeps two models (entity and DTO) apart by putting the conversion in one place. In .NET 10 there are three common options:
ProjectTo. Since v15.0 (July 2025) it's dual-licensed RPL-1.5/commercial (Lucky Penny Software), free for companies under US$5M revenue.IQueryable projections.The bigger win is often where you map. Projecting with Select in the query fetches only the needed columns, skips tracking and avoids lazy-loading N+1. Loading entities and mapping them afterwards over-fetches. The trade-off is convenience against explicitness, licence cost and run-time surprises.
Last updated 18 Nov 2026.