LESSON 4 OF 18

4. DTO Design, Mapping, and API Contracts

Learn how to design DTOs for Product and Category, apply manual mapping, and keep the public API contract separate from the database entity model.

45 dk 90

Introduction

The data model exposed by a REST API should not usually be identical to the entity model used by the database. Entity classes are designed for persistence, relationships, ORM behavior, and internal application needs. API consumers need a stable, understandable contract that contains only the data required for a particular operation. This is why APIs use Data Transfer Objects, commonly called DTOs.

In this lesson, we will design listing, detail, create, and update DTOs for Product and Category resources. We will then implement manual mappings between entities and DTOs. The goal is not merely to write property assignments. The goal is to make the public contract explicit, controlled, and independent from the database model.

Core principle: An entity is an internal data model; a DTO is a communication contract with the client.

Why are DTOs necessary?

Returning a Product entity directly from a controller may appear convenient at first. Over time, however, this approach creates several problems:

  • Database-specific or technical fields may leak to clients.
  • Navigation properties can create large or circular JSON graphs.
  • Every new entity property may unintentionally change the API response.
  • Clients may submit fields that they should not be allowed to modify.
  • Database schema changes can unintentionally become breaking API changes.

DTOs reduce these risks. They also allow different shapes for different use cases. A list screen may need a compact summary, while a detail screen may require additional information. A create request and an update request usually should not contain exactly the same fields.

Defining the entity and DTO boundary

Consider the following domain model:

public class Product {    public int Id { get; set; }    public string Name { get; set; } = string.Empty;    public decimal Price { get; set; }    public int StockQuantity { get; set; }    public bool IsActive { get; set; }    public DateTime CreatedAtUtc { get; set; }    public int CategoryId { get; set; }    public Category? Category { get; set; } } public class Category {    public int Id { get; set; }    public string Name { get; set; } = string.Empty;    public ICollection<Product> Products { get; set; } = []; }

These classes can serve as persistence models, but they should not automatically become the public API contract. Instead, define separate types for the API. Property names and types should remain consistent with the sample project. In a real application, entities may also contain concurrency tokens, soft-delete flags, or audit fields that should not be exposed to clients.

Separate DTOs by purpose

Rather than using one ProductDto for every scenario, define DTOs according to their purpose.

  • List DTO: Contains the compact fields needed in collection responses.
  • Detail DTO: Describes the representation of one resource in detail.
  • Create DTO: Contains fields the client is allowed to submit when creating a resource.
  • Update DTO: Limits the fields that may be changed during an update.

For example, the client should not choose the Id, CreatedAtUtc, or usually the initial IsActive value. These fields may appear in a response DTO, but they should not automatically appear in a create or update DTO.

Product DTOs

public sealed record ProductListDto(    int Id,    string Name,    decimal Price,    string CategoryName); public sealed record ProductDetailDto(    int Id,    string Name,    decimal Price,    int StockQuantity,    bool IsActive,    DateTime CreatedAtUtc,    CategorySummaryDto? Category); public sealed record ProductCreateDto(    string Name,    decimal Price,    int StockQuantity,    int CategoryId); public sealed record ProductUpdateDto(    string Name,    decimal Price,    int StockQuantity,    int CategoryId,    bool IsActive);

Separating response models from request models is important. ProductCreateDto does not contain the identifier or creation timestamp generated by the system. ProductUpdateDto explicitly lists the fields that may be updated. Validation rules can later be applied to these request types.

Category DTOs

public sealed record CategorySummaryDto(    int Id,    string Name); public sealed record CategoryListDto(    int Id,    string Name,    int ProductCount); public sealed record CategoryDetailDto(    int Id,    string Name,    IReadOnlyCollection<ProductListDto> Products); public sealed record CategoryCreateDto(string Name); public sealed record CategoryUpdateDto(string Name);

For a Category detail response, we use a Product list DTO instead of returning every Product entity. This avoids exposing the complete entity graph and keeps the response shape under control.

Manual mapping

Manual mapping means explicitly writing the conversion between an entity and a DTO. Although this creates some additional code, it makes the transformation visible. In small and medium-sized APIs, this is useful for debugging, code review, and custom transformation rules.

public static class ProductMappings {    public static ProductListDto ToListDto(this Product product)    {        return new ProductListDto(            product.Id,            product.Name,            product.Price,            product.Category?.Name ?? "Uncategorized");    }    public static ProductDetailDto ToDetailDto(this Product product)    {        return new ProductDetailDto(            product.Id,            product.Name,            product.Price,            product.StockQuantity,            product.IsActive,            product.CreatedAtUtc,            product.Category is null                ? null                : new CategorySummaryDto(                    product.Category.Id,                    product.Category.Name));    }    public static Product ToEntity(this ProductCreateDto dto)    {        return new Product        {            Name = dto.Name.Trim(),            Price = dto.Price,            StockQuantity = dto.StockQuantity,            CategoryId = dto.CategoryId,            IsActive = true,            CreatedAtUtc = DateTime.UtcNow        };    }    public static void ApplyTo(        this ProductUpdateDto dto,        Product product)    {        product.Name = dto.Name.Trim();        product.Price = dto.Price;        product.StockQuantity = dto.StockQuantity;        product.CategoryId = dto.CategoryId;        product.IsActive = dto.IsActive;    } }

ToEntity creates a new entity, while ApplyTo updates an existing entity. This prevents a client from changing fields such as Id or CreatedAtUtc during an update.

Using DTOs in a controller

The controller should accept and return DTOs rather than exposing entities. The following example demonstrates list and detail operations:

[ApiController] [Route("api/products")] public class ProductsController : ControllerBase {    private readonly AppDbContext _db;    public ProductsController(AppDbContext db)    {        _db = db;    }    [HttpGet]    public async Task GetAll(        CancellationToken cancellationToken)    {        var products = await _db.Products            .AsNoTracking()            .Include(p => p.Category)            .OrderBy(p => p.Name)            .ToListAsync(cancellationToken);        return Ok(products.Select(p => p.ToListDto()).ToArray());    }    [HttpGet("{id:int}")]    public async Task GetById(        int id,        CancellationToken cancellationToken)    {        var product = await _db.Products            .AsNoTracking()            .Include(p => p.Category)            .SingleOrDefaultAsync(p => p.Id == id, cancellationToken);        if (product is null)        {            return NotFound();        }        return Ok(product.ToDetailDto());    } }

ActionResult<T> documents the successful response type while still allowing alternatives such as NotFound. During creation, convert the request DTO to an entity, save it, and create a response DTO:

[HttpPost] public async Task Create(    ProductCreateDto dto,    CancellationToken cancellationToken) {    var categoryExists = await _db.Categories        .AnyAsync(c => c.Id == dto.CategoryId, cancellationToken);    if (!categoryExists)    {        return BadRequest("The specified category does not exist.");    }    var product = dto.ToEntity();    _db.Products.Add(product);    await _db.SaveChangesAsync(cancellationToken);    await _db.Entry(product)        .Reference(p => p.Category)        .LoadAsync(cancellationToken);    return CreatedAtAction(        nameof(GetById),        new { id = product.Id },        product.ToDetailDto()); }

The important point is that the entity is not returned to the client. Generated values such as the identifier and creation timestamp are exposed through the controlled response DTO.

Creating DTOs directly with projection

For list and detail queries, it is not always necessary to load complete entities and map them afterward. Entity Framework Core can use a Select projection to retrieve only the columns needed by the DTO.

var products = await _db.Products    .AsNoTracking()    .OrderBy(p => p.Name)    .Select(p => new ProductListDto(        p.Id,        p.Name,        p.Price,        p.Category == null ? "Uncategorized" : p.Category.Name))    .ToListAsync(cancellationToken);

This can reduce unnecessary column reads and improve list queries, especially for large tables. However, when transformations are complex or reusable domain rules are involved, a manual mapping method may be easier to understand. If both approaches are used in the same project, the reason for each choice should remain clear.

Protecting the API contract

DTOs are not only a security boundary; they are also a contract that must be maintained. Adding a new response property is often backward-compatible for existing clients. Removing a property, renaming it, or changing its type can be a breaking change.

  • Do not change JSON property names without a clear compatibility plan.
  • Check client usage before removing an existing property.
  • Do not combine response and request DTOs unnecessarily.
  • Never serialize entity navigation properties directly as a default strategy.
  • Exclude fields that the client must not control from request DTOs.
  • Choose DTO names that communicate their purpose.

Common mistakes

Using the entity as the request model

An action such as public Task<IActionResult> Create(Product product) may allow clients to submit fields such as IsActive or CreatedAtUtc. Use a ProductCreateDto containing only permitted fields instead.

Trying to solve every operation with one DTO

Combining list, detail, create, and update needs in one class increases unnecessary fields and ambiguous behavior. Keep each DTO focused on one responsibility.

Assuming related data is never null

The expression product.Category.Name can fail if the relationship was not loaded or is nullable. Mapping code should explicitly handle the possibility of a missing category.

Returning an entity from one endpoint

Returning an entity from even one endpoint makes the public contract inconsistent. All public endpoints should follow the response DTO strategy.

Practice exercise

  1. Create ProductListDto, ProductDetailDto, ProductCreateDto, and ProductUpdateDto.
  2. Change existing GET endpoints that return Product entities to return response DTOs.
  3. Add create and update request DTOs for Category.
  4. When creating a Product, verify that the referenced CategoryId exists.
  5. Write a manual mapping class and use a Select projection in at least one query.
  6. Test that the client cannot change Id or CreatedAtUtc.

Conclusion

DTO design is one of the fundamental techniques for defining the boundary between an API and a database. We created separate models for Product and Category listing, detail, creation, and update scenarios instead of exposing entities directly. We kept transformations explicit with manual mapping and examined how projection can select only the required data.

In the next lesson, we will apply validation rules to these DTOs. This will allow us not only to define a clear contract, but also to consistently verify that incoming client data conforms to it.

Sources