skip to content

DTO Mapping

Separating request and response DTOs from EF Core entities stops over-posting and leaked columns, mapped by hand or by a library. Interviewers ask where mapping code lives and how it stays correct.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In an ASP.NET Core 10 Minimal API, what goes wrong when GET /employees/{id} returns the EF Core Employee entity instead of an EmployeeDto record?

level: juniorimportance: must knowfreq 72%

answer

  1. System.Text.Json writes every public property
  2. Salary and BankAccount in the response
  3. Manager and Reports: a possible object cycle
  4. the JSON contract follows the table
  5. sealed record EmployeeDto(...) via TypedResults.Ok

basics

~20 s

Returning the entity hands System.Text.Json every public property, so Salary and any column added later leak, loaded navigations can throw an object-cycle JsonException, and the JSON contract changes whenever the table does. A response record lists exactly what is public.

solid answer

~50 s

A Minimal API serializes whatever the handler returns with `System.Text.Json`, which writes **every public readable property**. On an EF Core `Employee` that means `Salary`, `BankAccount` and whatever column someone adds next month. Navigation properties make it worse: if `Manager` and `Reports` were loaded, the graph points back at itself and the serializer throws a `JsonException` about a possible object cycle; if they were not loaded, the client sees `null`s that look like data. The response shape is also welded to the database schema, so a column rename silently renames a JSON field, and the OpenAPI document describes the entity. The fix is a response type, typically `public sealed record EmployeeDto(int Id, string FullName, string Email, string Department);`, filled from the entity and returned with `TypedResults.Ok(dto)`. Adding a field to the API then becomes a deliberate code change.

code

csharp · 13 lines
csharp
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; } = "";
    public string LastName { get; set; } = "";
    public string Email { get; set; } = "";
    public decimal Salary { get; set; }          // written to JSON if the entity is returned
    public string BankAccount { get; set; } = ""; // so is this
    public Employee? Manager { get; set; }       // cycle with Reports when loaded
    public List<Employee> Reports { get; set; } = [];
}

public sealed record EmployeeDto(int Id, string FullName, string Email, string Department);

go deeper

for a junior

Remember that the serializer writes every public property, so an entity leaks columns like Salary, and that a response record lists only what the client should see.

for a middle

Explain the object-cycle JsonException from loaded navigations, the null-versus-not-loaded ambiguity, and why a positional record gives an allow-list and a stable contract.

for a senior

Argue why deny-lists such as [JsonIgnore] and IgnoreCycles decay, and set a team rule that endpoints return DTOs with metadata like Results<Ok<EmployeeDto>, NotFound>.

for a principal

Weigh the duplication of DTOs against the cost of a contract that changes with every migration, and decide where the boundary between persistence and API types sits.

## What the framework actually does with your return value In ASP.NET Core 10 a Minimal API handler that returns an object — directly, or wrapped in `TypedResults.Ok(value)` — has it written as JSON by **System.Text.Json** using the app's `JsonOptions` (web defaults: camelCase names). The serializer does not know or care that the object came from EF Core. It walks the object's public properties and writes each one. That is the whole problem with returning an entity: the entity's shape is decided by the database model, and the API's shape silently becomes the same thing. ## Four ways the entity hurts you 1. **Leaked columns.** An HR `Employee` entity has `Salary`, `BankAccount`, `NationalId` and an internal `PerformanceNote`. Every one of them is public because EF Core maps public properties. All of them go to every caller of `GET /employees/{id}`, and a column added later leaks on its first deploy without anyone touching the endpoint. 2. **Navigation cycles.** EF Core fixes up navigations in both directions: an employee's `Manager` is an `Employee` whose `Reports` contains the first employee again. When those are loaded, System.Text.Json follows them until it detects a possible object cycle and throws a `JsonException`, and the request fails with a 500. `ReferenceHandler.IgnoreCycles` hides the exception but still writes a deep, half-repeated graph. 3. **Half-loaded graphs.** When navigations are not loaded, the response contains `"department": null` — which a client reads as "no department", not "not fetched". With lazy-loading proxies turned on, serialization instead triggers an extra query for each navigation it touches, after the handler thought it was done. 4. **A contract welded to the schema.** Renaming `Surname` to `LastName` in a migration renames a JSON field that mobile clients rely on. The generated OpenAPI document also describes the entity, so the leak is documented as well as shipped. ## The response record A **DTO** (data transfer object) is a type that exists only to be serialized. A positional record is the usual shape in current C#: ```csharp public sealed record EmployeeDto(int Id, string FullName, string Email, string Department); app.MapGet("/employees/{id:int}", async Task<Results<Ok<EmployeeDto>, NotFound>> (int id, HrDb db) => { var dto = await db.Employees .Where(e => e.Id == id) .Select(e => new EmployeeDto(e.Id, e.FirstName + " " + e.LastName, e.Email, e.Department.Name)) .FirstOrDefaultAsync(); return dto is null ? TypedResults.NotFound() : TypedResults.Ok(dto); }); ``` What the record buys: - **An allow-list.** Only the four listed members exist, so nothing else can be serialized, today or after the next migration. - **No graph.** `Department` is a string, so there is no navigation to cycle through and nothing for a lazy proxy to load. - **A stable contract.** The record changes only when someone edits it, in a diff a reviewer can see. - **Immutability.** A positional record's properties are `init`-only, so a handler cannot half-mutate it after mapping. - **Accurate metadata.** `Results<Ok<EmployeeDto>, NotFound>` tells the OpenAPI generator the real response schema. ## Where the mapping lives Three common homes, all fine when used consistently: | Approach | Looks like | Good for | |---|---|---| | Inline projection | `.Select(e => new EmployeeDto(...))` in the query | Reads: only the projected columns are fetched | | Extension method | `employee.ToDto()` in a static `EmployeeMappings` class | Objects already in memory, e.g. after a create | | Mapping library | a source-generated or configured mapper | Many similar maps; see the library trade-offs | Requests deserve the same treatment in the other direction — an `UpdateEmployeeRequest` record rather than the entity as a body parameter — because binding a body onto an entity lets callers write columns they should never touch. ## When returning the entity is tolerable A throwaway prototype, an internal admin tool whose entity has nothing sensitive, or a read model class that exists only for the endpoint and is not the write entity. Even then, the moment the type gains a navigation or a private-by-policy column, the shortcut becomes the incident.

  • Why is ReferenceHandler.IgnoreCycles not a fix for returning entities?
    It only stops System.Text.Json from throwing on the `Manager`/`Reports` cycle by writing `null` where a reference repeats. Every other public property, including `Salary`, is still serialized, the graph can still be large, and the JSON shape still follows the schema. It treats the symptom the cycle produces, not the leak or the coupling.
  • Would [JsonIgnore] on Employee.Salary be enough?
    It stops that one property being written, but it is a deny-list on the persistence type: the next sensitive column is public until someone remembers to annotate it, and the attribute also changes how the entity reads JSON anywhere else it is serialized. A response record is an allow-list, so new columns stay private by default.

  • Returning the entity is fine because EF Core only exposes mapped columns
  • Setting ReferenceHandler.IgnoreCycles makes returning entities safe
  • System.Text.Json skips properties that have no value in the database
  • [JsonIgnore] on sensitive entity properties is a complete long-term fix
  • A DTO is only needed when the API uses different property names
open as a page

In ASP.NET Core with EF Core, why does a PUT handler that binds the body to the Employee entity and calls db.Update let a caller rewrite Salary?

level: middleimportance: must knowfreq 55%

basics

~20 s

The JSON body is deserialized straight onto Employee, so any property the caller sends, Salary included, is set, and any it omits arrives as a default. db.Update then marks every column modified, so SaveChanges writes both into the row.

open as a page

In an ASP.NET Core 10 codebase, how do you test DTO mappings so a new Employee column is neither silently dropped nor leaked into a response?

level: middleimportance: should knowfreq 33%

basics

~20 s

Match the safety net to the mapper: compile errors from positional records for hand-written code, AssertConfigurationIsValid in a unit test for AutoMapper, Mapperly's RMG012 and RMG020 raised to errors, plus one response-level test that the JSON contains no salary.

open as a page

With EF Core 10 in an ASP.NET Core API, why can .Select(e => e.ToDto()) read every Employee column while .Select(e => new EmployeeDto(...)) reads only the projected ones?

level: seniorimportance: should knowfreq 42%

basics

~20 s

EF Core cannot see inside a compiled ToDto method, so it evaluates that final Select on the client: it loads the whole Employee row, Salary included, and tracks it. An inline new EmployeeDto(...) is an expression EF Core translates into a SELECT of just those columns.

open as a page

After AutoMapper became a commercial Lucky Penny product in 15.0, how would you choose a mapping approach for a large ASP.NET Core codebase that uses it everywhere?

level: principalimportance: should knowfreq 30%

basics

~20 s

Treat it as a licence decision plus a migration-cost decision: AutoMapper 15+ is RPL-1.5 or commercial, enforced only by log messages, while Mapperly is an Apache-2.0 source generator. Inventory how the codebase uses AutoMapper, then pay, migrate gradually, or hand-write.

open as a page