Why DTOs?

Jon Smith edited this page Jan 21, 2015 · 5 revisions

I believe that in any reasonably complex application the data model should be defined by the business process/data and not by how the user wants to see the data (see Domain-Driven Design for more about this type of approach). So, for instance the name of a customer may be stored in the database as Title, FirstName, LastName to allow for different sorting, but the display to a casual user would just want the full name.

The solution is to shape/transform the data between the lower layers, i.e. the Data Layer and the Business Layer, and the Presentation layer. We then present data classes more attuned to the Presentation Layer's need. This process is normally done in the Service Layer (see Architecture Overview) and we call these type of classes Data Transfer Objects - DTOs.

In fact if you have used ASP.NET MVC before you will have come across these type of classes already. In MVC they are often called ViewModels and are normally stored in Models folder in your MVC application. I use the more generic term DTOs GenericServices, but ViewModels are the same as DTOs in this case.

The problem of DTOs

As the article in the 'Data Transfer Objects - DTOs' link above says, using DTOs can be hard work. I can attest to that as I hand coded data<->DTO coping in a medium sides application and there was a lot of code and most of it was boring and repetitive! That is why I developed GenericServices.

Solving the problem of DTOs

GenericServices does three things to make using DTOs much easier.

  1. GenericServices automates the data<->DTO copying for us uses AutoMapper. AutoMapper uses a convention-based mapping method. You can read how this all works in DTO data copying.
  2. GenericServices has the concept of Calculated properties. These allow you to create new properties that combine, aggregate or generally change the existing properties into a more useful form for the presentation layer. See this article for more on this.
  3. GenericServices provides two DTO abstract classes, EfGenericDto for normal sync operations and EfGenericDtoAsync for async (parallel) operations to act as a base for your DTOs. These classes hold all the variables and logic for controlling the data access operations, any part of which can be tapped into to handle specific needs. I suggest you look at the items under the Data Transfer Objects (DTOs) at the bottom of the Wiki sidebar for more information on that.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.