.NET Beyond the Demos - Part 3 - The DTOs

Part 1 - Introduction
Part 2 - The Architecture
Part 3 - The DTOs (This post)

To make passing data between the various parts of our application easy, we need a way to encapsulate that data in such a way that it can easily be transported across the network and consumed by various clients.

The solution comes in the form of a "Data Transfer Object" or DTO. These could also be referred to as Models, but they're not quite the same thing.

The DTO Lifecycle

The Data Transfer Object

Starting with the database, we retrieve data using the repository. This gives us an Entity (or model). We then map this to a DTO for use by the Web Api. The web api passes the DTO back in response to the client request for data. Since a DTO is a simple object, it can easily be serialized into JSON or XML (the serialization formats for Web Api).

When the client reads the DTO, it can deserizalize the JSON or XML into the same DTO for consumption by the client application.

Saving data works the same, but in reverse.

Since we control all parts of this system, we can share the same code library containing the DTOs across all layers of the application, reusing the exact same code.

This also allows us to have a common client that knows how to manage the DTOs that we can use in multiple client applications, including ASP.NET MVC, UWP, Android, or iOS (using Xamarin).

What does a DTO look like?

The code for a DTO is simple, but we'll also throw in an interface to make it more powerful to use with our client. We'll see why the interface is important later on.

The IDto Interface code

This is the most basic interface, but you can add more if your DTOs require more functionality.

public interface IDto 
{
  long Id { get; set; }
}

The DTO code

Here is an example DTO for a fictitious account object.

public class AccountDto : IDto
{
  public long Id { get; set; }
  public long ClientId { get; set; }
  public string AccountName { get; set; }
  public double? Balance { get; set; }
}

Usage

DTOs and Entities do not always have a 1-1 relationship. Sometimes, it makes sense to flatten a group of related entities out into a single DTO for ease of use in the application.

Michael Earls

Michael Earls

Michael has been a computer nerd since he was ten years old and he begged his parents to buy him a computer for Christmas. In 1982, he was the proud owner of a TI-99/4A. He's been coding since.

Read More