LESSON 3 OF 16

3. Domain Models, DTOs, and Data Contracts

This lesson explains entities, request DTOs, response DTOs, and view models, then applies them to secure and maintainable API data contracts.

75 dk 106

Introduction

In the previous lesson, we created the solution structure and separated the application layers. This lesson focuses on the shapes of the data exchanged between those layers. In a well-designed application, separating projects is not enough; each boundary should also have a clear data contract.

Our example is a small task-management application. Users will create tasks, list tasks, and update task status. The database model, the data accepted by the API, and the data needed by a web page do not have to be identical. We will therefore create models for specific responsibilities instead of passing one class through the entire system.

Understanding the model types

Entity model

An entity represents an object in the business domain that is usually persisted in the database. It may contain database keys, relationships, audit fields, internal notes, or other information that should remain inside the application.

namespace TaskApp.Domain.Entities;

public class TaskItem
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string? Description { get; set; }
    public bool IsCompleted { get; set; }
    public string? InternalNote { get; set; }
    public DateTime CreatedAtUtc { get; set; }
    public DateTime? UpdatedAtUtc { get; set; }
}

The InternalNote property might be used only by administrators or support staff. If clients do not need it, the entity should not be serialized directly as an API response. Entities can also contain persistence-related details that should not become part of a public API contract.

Request DTO

A request DTO defines the data that a client is allowed to send to the server. Create and update operations often require different inputs, so separate DTOs are usually clearer than one universal request class.

namespace TaskApp.Application.Tasks.Dtos;

public sealed record CreateTaskRequest(
    string Title,
    string? Description);

public sealed record UpdateTaskRequest(
    string Title,
    string? Description,
    bool IsCompleted);

With this design, the client is not expected to provide Id, CreatedAtUtc, or InternalNote. Those values are controlled by the server. Even if a client adds unexpected JSON properties, the application should only use fields explicitly defined by the request contract.

Response DTO

A response DTO defines the data returned by the API. It can contain fewer fields than the entity, use different names, or expose a shape designed specifically for API consumers.

namespace TaskApp.Application.Tasks.Dtos;

public sealed record TaskResponse(
    int Id,
    string Title,
    string? Description,
    bool IsCompleted,
    DateTime CreatedAtUtc);

The InternalNote property is intentionally absent. Therefore, it cannot accidentally appear in the JSON response through ordinary entity serialization. A response contract should contain the fields consumers genuinely need, not every field available in the database.

View model

A view model is shaped around a particular web page or UI component. It may resemble an API response, but it has a different responsibility. For example, a task list may need display-ready values:

public sealed record TaskListItemViewModel(
    int Id,
    string Title,
    string StatusText,
    string CreatedDateText);

The web application can convert a UTC timestamp into the user's local time and format it as text. That presentation concern should not be forced into the API response DTO.

Why data contracts matter

A data contract is an agreement between two components about the data they exchange. For a REST API, it includes endpoint paths, HTTP methods, request bodies, response bodies, data types, and error representations. Without an explicit contract, a web client, mobile client, and third-party consumer may interpret the same endpoint differently.

ModelDirectionPurposeExample fields
EntityApplication-databaseRepresent persisted dataId, CreatedAtUtc, InternalNote
Request DTOClient-APILimit accepted inputTitle, Description
Response DTOAPI-clientProduce safe outputId, Title, IsCompleted
View modelWeb application-viewSupport a page's presentation needsStatusText, CreatedDateText

This separation reduces coupling. The API does not expose every entity detail, the Application layer works with use-case-specific inputs and outputs, and the Web layer can shape data for a particular screen.

Step-by-step implementation

1. Organize projects and folders

In the solution created in the previous lesson, entities can remain in the Domain project while DTOs can be placed under the Application project:

TaskApp.Domain
  Entities/

TaskApp.Application
  Tasks/
    Dtos/
    Interfaces/
    Services/

TaskApp.Api
  Controllers/

Keeping DTOs close to the application use cases makes their purpose visible. Different folder conventions are also valid. The essential rule is to avoid making API controllers depend directly on persistence entities when a public contract is required.

2. Add validation rules to request DTOs

Basic input rules can be expressed on request DTOs. For example, a title can be required and limited in length:

using System.ComponentModel.DataAnnotations;

public sealed class CreateTaskRequest
{
    [Required]
    [StringLength(120, MinimumLength = 3)]
    public string Title { get; init; } = string.Empty;

    [StringLength(1000)]
    public string? Description { get; init; }
}

These attributes describe structural validation. A rule such as “there must not be another open task with the same title” requires application data and belongs in a service or domain rule. DTO validation is useful, but it is not a replacement for business validation.

3. Map between entities and DTOs

The conversion should be explicit and controlled. Manual mapping is a good starting point because every transferred property is visible:

public static class TaskMappings
{
    public static TaskItem ToEntity(this CreateTaskRequest request)
    {
        return new TaskItem
        {
            Title = request.Title.Trim(),
            Description = request.Description?.Trim(),
            IsCompleted = false,
            CreatedAtUtc = DateTime.UtcNow
        };
    }

    public static TaskResponse ToResponse(this TaskItem entity)
    {
        return new TaskResponse(
            entity.Id,
            entity.Title,
            entity.Description,
            entity.IsCompleted,
            entity.CreatedAtUtc);
    }
}

The client does not supply the identifier or creation timestamp; the server controls them. Simple normalization such as trimming can happen during mapping, while larger business decisions should remain in the application or domain layer.

4. Return a response DTO from the controller

The controller can translate the service result into a response DTO and then produce an HTTP response:

[ApiController]
[Route("api/tasks")]
public sealed class TasksController : ControllerBase
{
    private readonly ITaskService _taskService;

    public TasksController(ITaskService taskService)
    {
        _taskService = taskService;
    }

    [HttpGet("{id:int}")]
    public async Task GetById(int id)
    {
        var task = await _taskService.GetByIdAsync(id);

        if (task is null)
        {
            return NotFound();
        }

        return Ok(task.ToResponse());
    }
}

ActionResult<TaskResponse> communicates both the expected successful data type and the possible HTTP results. The controller should coordinate HTTP concerns and application calls; it should not contain database queries or complex business rules.

Security and maintainability guidelines

  • Do not return entities directly: internal fields, relationships, and future sensitive properties could be exposed accidentally.
  • Do not trust client-provided identifiers: locate the resource from the route and verify that the current user is allowed to access it.
  • Reduce mass-assignment risk: never copy every incoming property automatically into an entity without an explicit allow-list.
  • Keep secrets out of DTOs: password hashes, internal tokens, and private operational data should not be response fields.
  • Control entity relationships: serializing navigation properties directly can produce unnecessary payloads or reference cycles.
  • Handle dates consistently: storing and transferring UTC values while formatting them at the presentation boundary avoids many time-zone problems.

Common mistakes

Using one model everywhere

A single class for the database, API requests, API responses, and views may reduce code initially. However, every new property becomes visible across all boundaries. A database change can unintentionally break clients. Separate models by responsibility instead.

Assuming DTOs replace authorization

DTOs help control the data shape, but they do not decide who may access a resource. A user must not retrieve another user's task merely because the response DTO omits some fields. Authorization remains an explicit application concern.

Leaving nullability undefined

Can Description be empty or absent? That decision should be clear in the C# type, validation rules, database design, and API documentation. Ambiguous nullability leads to inconsistent client behavior and avoidable runtime errors.

Putting every mapping operation in controllers

Large controllers become difficult to read when they contain dozens of conversions. Manual mapping is suitable for small examples; larger applications can use dedicated mapping classes or a mapping library. Automatic mapping should still be reviewed carefully so that hidden conventions do not expose or overwrite fields.

Short practice exercise

Complete the following exercise:

  1. Add an InternalNote property to TaskItem that is intended for server-side use only.
  2. Create CreateTaskRequest and TaskResponse types.
  3. Require a title between 3 and 120 characters.
  4. Write a mapping method from the entity to the response DTO.
  5. Verify that client-supplied Id and CreatedAtUtc values are ignored during creation.
  6. Test that InternalNote does not appear in the response JSON.

As an extension, create a TaskListItemViewModel for a web page and convert the UTC creation date into display text at the Web layer.

Conclusion

This lesson distinguished entities, request DTOs, response DTOs, and view models. Explicit data contracts improve API security, clarity, and long-term maintainability. Accept only the fields the client is allowed to send, return only the data the client needs, and make conversions deliberate.

In the next lesson, we will use these models while designing Application services and repository contracts. This will make the workflow between the API controller and the database more explicit and easier to test.

Sources