C# / .NET Compendium PLEN
.NET / C# / Refresher / web patterns

Where to put DTOs in an MVVM (WPF) project

The problem - a DTO lives "between" layers

A DTO (Data Transfer Object) is an object representing data in the form in which it travels between layers (e.g. from a Web API to a WPF client) - it is neither a pure domain Model nor a ViewModel. The question "where to put it" touches the fundamental structure of the project.

A typical WPF project structure with DI (a link to the earlier discussion)

MyApp/
├── Models/              ← The domain Model (if local, not only through the API)
│   └── User.cs
├── DTOs/                ← DTO - format wymiany danych z API
│   └── OrderDto.cs
├── Services/            ← services, API clients (Services/OrderApiClient.cs from the earlier discussion)
│   ├── IOrderApiClient.cs
│   └── OrderApiClient.cs
├── ViewModels/
│   ├── ViewModelBase.cs
│   └── OrderDetailsViewModel.cs
├── Views/
│   └── OrderDetailsView.xaml

The DTO lives in a separate DTOs/ folder (or Contracts/), parallel to Models/ - this is a key architectural decision: a DTO is not a domain Model, even though they may look similar.

Why NOT to use a DTO directly as a Property in the ViewModel (a common mistake)

// ❌ A questionable practice - the ViewModel operates directly on the DTO from the API
public class OrderDetailsViewModel : ViewModelBase
{
    private OrderDto _order; // DTO z API, jako typ Property ViewModelu
    public OrderDto Order
    {
        get => _order;
        set => SetProperty(ref _order, value);
    }
}

The problem: the DTO is designed for the API contract (the JSON format), not for the needs of the UI. If the server changes the API contract (e.g. renames a field), the ViewModel and the XAML binding break at the same time - the DTO "leaks" through all the layers right up to the UI.

A better approach - a separate model for the UI (sometimes called a "Presentation Model", or simply properties on the ViewModel itself)

// DTOs/OrderDto.cs - kontrakt z API, format 1:1 z JSON
public record OrderDto(int Id, string CustomerName, decimal TotalAmount, string Status, DateTime CreatedAt);
// ViewModels/OrderDetailsViewModel.cs - properties matched to the UI's NEEDS, not to the API contract
public class OrderDetailsViewModel : ViewModelBase
{
    private readonly IOrderApiClient _apiClient;

    private int _orderId;
    public int OrderId { get => _orderId; set => SetProperty(ref _orderId, value); }

    private string _customerName;
    public string CustomerName { get => _customerName; set => SetProperty(ref _customerName, value); }

    // A COMPUTED property, needed ONLY in the UI - the DTO doesn't have it and shouldn't
    private string _formattedTotal;
    public string FormattedTotal { get => _formattedTotal; set => SetProperty(ref _formattedTotal, value); }

    // A colour/status specific to DISPLAY - also makes no sense in the DTO
    private Brush _statusColor;
    public Brush StatusColor { get => _statusColor; set => SetProperty(ref _statusColor, value); }

    public OrderDetailsViewModel(IOrderApiClient apiClient) => _apiClient = apiClient;

    public async Task LoadOrderAsync(int id)
    {
        var result = await _apiClient.GetOrderAsync(id); // pobiera DTO z API

        if (result.IsSuccess)
        {
            var dto = result.Value;

            // MAPPING from the DTO to the ViewModel's properties - this is where the "decoupling" happens
            OrderId = dto.Id;
            CustomerName = dto.CustomerName;
            FormattedTotal = dto.TotalAmount.ToString("C"); // PRESENTATION logic, doesn't belong in the DTO
            StatusColor = dto.Status == "Shipped" ? Brushes.Green : Brushes.Orange; // logika UI
        }
    }
}

The key rule: the DTO enters the ViewModel (as a method parameter, a temporary variable), but doesn't remain as a Property bound in XAML - the ViewModel maps the data from the DTO onto its own properties, matched to the needs of the UI (formatted, computed, enriched with presentation logic).

When a DTO AS a Property is acceptable - simpler cases

For very simple ViewModels, where the DTO corresponds 1:1 to what the UI needs to display (with no transformation), using the DTO directly can be a pragmatic compromise - but you have to be aware of it as a decision, not as an accidental consequence of "it was easier":

// Acceptable for a SIMPLE list where the UI displays the data 1:1
public class OrderListViewModel : ViewModelBase
{
    public ObservableCollection<OrderDto> Orders { get; } = new(); // ObservableCollection from the earlier discussion of WPF
}

This is a practical compromise - for a list displaying simple data with no additional presentation logic, creating a separate "Presentation Model" can be unnecessary overhead.

AutoMapper - a natural use here (a link to the earlier discussion)

// A Profile mapping the DTO to the ViewModel's "model", if the differences are non-trivial
public class OrderPresentationMappingProfile : Profile
{
    public OrderPresentationMappingProfile()
    {
        CreateMap<OrderDto, OrderPresentationModel>()
            .ForMember(dest => dest.FormattedTotal, opt => opt.MapFrom(src => src.TotalAmount.ToString("C")))
            .ForMember(dest => dest.StatusColor, opt => opt.MapFrom(src => src.Status == "Shipped" ? "Green" : "Orange"));
    }
}

Summary - a practical rule

A DTO should live in a separate folder/namespace (DTOs/), representing only the contract of communication with the API - never a domain Model. In the ViewModel, the DTO passes through the data-loading methods, but for non-trivial cases (a need for formatting, presentation logic, computed properties) it should be mapped onto the properties of the ViewModel itself (or a dedicated "Presentation Model"), so that a change to the API contract doesn't directly break the binding in XAML. For simple, static lists without transformation, binding the DTO directly is a pragmatic, acceptable compromise.

Buy me a coffee