C# – One DTO per database table or one DTO per domain class

cdomain-driven-design

I recently asked this question: Return domain objects from the repository

I have come accross this article: http://enterprisecraftsmanship.com/2015/04/20/types-of-cqrs/. Option 1 and part of option 2 talk about having a Data Transfer Object for queries and domain objects for commands.

Say I have a domain object like this:

public class Order
{
  //Fields and properties for Order go here
  public List<OrderItem> OrderItems;
  //Methods for order go here.
}

What would the DTO(s) look like?

Option 1

The DTO looks identical to the domain object like this:

 public class OrderDTO
    {
      //Fields and properties for Order go here
      public List<OrderItemDTO> OrderItems;
      //Methods for order go here.
    }

i.e. one DTO would be returned to the application service containing Orders and Order Items.

Option 2a

There would be one DTO per database table (notice in the example below that there is no OrderItemDTO collection in OrderDTO:

public class OrderDTO
        {
          //Fields and properties for Order go here
          public List<OrderItemDTO> OrderItems;
          //Methods for order go here.
        }

public class OrderItemDTO
{
  //Fields and properties for OrderItem go here
          //Methods for OrderItem go here.
}

i.e. two DTO objects are returned to the application service.

Option 2b

Same as option 2 except I would put a collection of foreign keys (for OrderItemDTO in the Order class).

Which option is "better" i.e. option 1 or option 2.

Best Answer

My answer is, none of the above.

I create DTOs as and when is necessary to suit the shape of data projected from my data access operations. My applications tend towards a CQRS architecture and as a result my DTOs represent the specific needs of queries or commands.

And to continue, I was about to hit the send button without reading the article you linked to.

Having now read it, the article is very interesting but you have only presented the two least sophisticated DTO categories (0 and 1 in the article) of the four discussed.

Using the author's 0, 1, 2 and 3 DTO usage categories, I aspire to a pure category 3 design but lapse on occasion into category 2.

You have asked for a preference on some DTO examples in your question. From my perspective all of these these encourage an "entity server" architecture which I have little enthusiasm for.