📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is a Data Transfer Object (DTO)? Explain where the pattern comes from, why you shouldn't return or bind EF Core entities directly in an ASP.NET Core API (over-posting, leaking fields, versioning, serialisation cycles), why C# records make good DTOs, and where DTOs are and aren't needed.

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).

Junior Theory Beginner api-design aspnet-core design-patterns dto records security

🎯 Key points

  • DTO: a data-only object that carries data across a boundary (Fowler: batch several values into one remote call); no behaviour or business rules
  • Binding an entity lets clients over-post fields like IsAdmin or Balance (mass assignment)
  • Returning an entity leaks fields such as PasswordHash or date of birth, which you must protect under the Privacy Act 1988 (APP 11), and couples the API contract to the database schema
  • Navigation properties cause JSON cycles: System.Text.Json throws 'A possible object cycle was detected'; ReferenceHandler.IgnoreCycles only suppresses the error and still serialises an object graph instead of a contract
  • Separate request DTOs (CreateUserRequest) from response DTOs (UserResponse); each contains only what that operation needs
  • Positional records give concise, immutable DTOs with value equality and work with System.Text.Json and minimal APIs
  • DTOs belong at boundaries (HTTP, messages, between services), not between every internal layer

⏱ 30-second answer

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:

  • Over-posting: a client can send IsAdmin: true and the model binder sets it.
  • Leaking data: PasswordHash or a date of birth ends up in responses.
  • Coupling: renaming a column breaks every client.
  • Cycles: navigation properties make System.Text.Json throw an object-cycle error.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 User entity on POST, the client can include "isAdmin": true or "balance": 1000000 and the model binder happily sets it. That's over-posting, or mass assignment. If an endpoint returns the entity, every property goes out, including PasswordHash, 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 for ReferenceHandler.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 like UserResponse(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."


Entity vs DTO

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

Problems with exposing entities

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands the DTO as a boundary contract and can name the concrete risks of exposing entities.

Green flags

  • Names over-posting and data leakage specifically.
  • Mentions JSON cycles from navigation properties.
  • Separates request and response DTOs.
  • Uses records and explains why.
  • Keeps DTOs at boundaries.

Red flags

  • Returns entities "because it's simpler".
  • Puts logic in DTOs.
  • Suggests IgnoreCycles as the fix.

📚 Learn in depth

1. Origin

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

2. Over-posting in detail

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.

3. Serialisation cycles

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.

4. Records as DTOs

public sealed record UserResponse(Guid Id, string DisplayName, string Email);
  • One line generates constructor, properties (init-only), equality, ToString and deconstruction.
  • Immutable, so a DTO can't be changed after mapping.
  • System.Text.Json deserialises through the primary constructor.
  • Value equality makes test assertions simple (Assert.Equal(expected, actual)).

Record structs work too, but class records are the usual choice for API DTOs.

5. Request vs response 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.

6. Where DTOs aren't needed

  • Between layers inside the same process, if the domain object already fits.
  • Internal tools where the entity is the contract and nothing sensitive exists (rare, and usually temporary).

Try it yourself

  1. Bind a User entity in a minimal API POST and send "isAdmin": true; check the saved row.
  2. Return an Order with Customer.Orders loaded and read the JsonException.
  3. Replace both with request/response records and repeat.
  4. Add a column to the entity and confirm the response DTO doesn't change.
  5. Write a test that compares a response record with Assert.Equal.

💻 Code

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());
    }
}

⚠ Common mistakes

  • Mistake: Binding EF Core entities directly from the request body. Why it is wrong: Clients can set fields like IsAdmin or Balance (over-posting). Instead: Bind a request DTO that only contains settable fields.
  • Mistake: Returning entities from endpoints. Why it is wrong: Sensitive fields leak, and the API contract changes whenever the schema does. Instead: Return response DTOs with an explicit field list.
  • Mistake: Fixing JSON cycle errors with 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.
  • Mistake: Using one DTO for both requests and responses. Why it is wrong: Server-owned fields like Id and CreatedAt become bindable. Instead: Separate request and response types.
  • Mistake: Putting business logic or validation rules in DTOs. Why it is wrong: DTOs are contracts; logic there gets duplicated or bypassed. Instead: Keep rules in the domain; DTOs hold data only.
  • Mistake: Adding DTOs between every internal layer. Why it is wrong: Mapping the same shape repeatedly inside one process adds code and bugs for no protection. Instead: Use DTOs at boundaries only.
  • Mistake: Using [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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate explains why entities shouldn't be exposed Why: Checks the senior-level trade-offs between domain models and DTOs, including versioning and when sharing a type is acceptable
    How to answer

    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.

  2. When: Candidate says records make good DTOs because they're immutable Why: Checks immutability and why records suit DTOs
    How to answer

    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.

  3. When: Candidate mentions mapping code between entities and DTOs Why: Checks how to map between entities and DTOs, and projecting in the query
    How to answer

    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:

    • Hand-written mapping (extension methods or constructors): explicit, fast, compile-checked. The risk is forgetting a new property.
    • AutoMapper: convention-based run-time mapping with ProjectTo. Since v15.0 (July 2025) it's dual-licensed RPL-1.5/commercial (Lucky Penny Software), free for companies under US$5M revenue.
    • Mapperly: an Apache 2.0 source generator. It writes the mapping code at build time, reports unmapped members as diagnostics, is AOT-safe and can generate 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.

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me