99

I've seen a lot of questions related to mapping DTOs to Domain Objects, but I didn't feel they answered my question. I've used many methods before and have my own opinions but I'm looking for something a little more concrete.

The Situation:

We have many domain objects. We are using a CSLA model so our domain objects can be pretty complex and they contain their own data access. You do not want to pass these around on the wire. We are going to be writing some new services that will return data in a number of formats (.Net, JSON, etc.). For this (and other reasons) we are also creating a lean, data transfer object to pass around on the wire.

My question is: How should the DTO and Domain object be connected?

My first reaction is to use a Fowler, DTO pattern-type solution. I've seen this done many times and it feels right to me. The domain object contains no reference to the DTO. An outside entity (a "mapper" or "assembler") is called to create a DTO from a Domain Object. Normally there is an ORM on the domain object side. The downside of this is that the "mapper" tends to get extremely complex for any real situation and can be very fragile.

Another idea put forth is for the Domain Object to "contain" the DTO, since it's just a lean data object. The Domain Object properties would internally reference the DTO properties and could just return the DTO if asked for. I can see no problems with this but it feels wrong. I have seen some articles where people using NHibernate appeared to use this method.

Are there other ways? Is one of the ways above worth using? If so or if not, why?

5
  • 4
    The automapper looks interesting. I've seen plenty of code before that it would have replaced. My main issue there is that if I am going to be stuck with a ton of mapping code for whatever reason, I'd prefer to have control over it myself. Mar 24, 2009 at 16:44
  • 2
    When we go from DTOs to Domain Objects, that mapping is 100% manual. It's a much harder problem to solve, as we try to keep our domain objects operation-based, instead of merely data containers. Going to a DTO, that's an easy problem to solve. May 19, 2009 at 13:43
  • Another option is the beta version of ServiceToolkit.NET, which we started during our last project. Maybe it can help you: http://servicetoolkit.codeplex.com/
    – user187738
    Oct 10, 2009 at 18:19
  • I would agree that it is wrong in that the domain object should have no knowledge of the dto object. While they may be related in this case, their purpose is completely separate (dtos are generally made for purpose) and you'd be creating an unnecessary dependency. Nov 26, 2013 at 18:27
  • I think you are confusing a Data Transfer Object with an output model. A DTO is not just a slimmer version of a domain entity suitable for serialization. A DTO normally contains aggregated data shared between multiple domain entities, for which you'd otherwise need several rest calls. I'd recommand you to read Tom Hombergs "Getting your hands dirty on clean architecture". Jan 26 at 10:11

11 Answers 11

47

A benefit of having a mapper that sits between your domain and your DTO is not as appearent when you are only supporting a single mapping, but as the number of mappings increases, having that code isolated from the domain helps keep the domain simpler and leaner. You won't be cluttering your domain with a lot of extra weight.

Personally, I try and keep the mapping out of my domain entities and put the responsibility in what I call "Manager / Service layer". This is a layer that sits between the application and the respository(ies), and provides business logic such as workflow coordination (If you modify A, you might have to also modify B so service A will work with Service B).

If I had a lot of possible ending formats, I might look at creating a plugable formatter that could use the Visitor pattern, for example to transform my entities, but I've not found a need yet for anything this complex.

1
  • "(If you modify A, you might have to also modify B so service A will work with Service B)" - Doesn't this come under business logic? I think this part should go to controller right rather than service?
    – Ayyappa
    Jun 12, 2019 at 14:33
24

You could use an automapper such as the one written by Jimmy Bogard which has no connection between the objects and relies on naming conventions being adhered to.

4
  • 11
    Automapper could lead to accidentally exposed properties --> security hole. It would be better to say explicitly what should be exposed as a DTO.
    – deamon
    Jan 13, 2010 at 9:34
  • 4
    @deamon: valid concern, but so is the bugs (and potential security holes because of human oversight) that can be created writing all that gooey mapping code. I'll go the automagic road and handle the 5% using it's built in custom mapping feature.
    – Merritt
    Sep 1, 2010 at 20:18
  • @deamon - can't you just do the conditional mapping for those properties that you shouldn't be exposing? Thinking AutoMapper handles that scenario?
    – Richard B
    Feb 8, 2013 at 20:15
  • 1
    If you use AutoMapper, I think it's extremely important that you have all the unit tests in place to test whether the mapping is done correctly.
    – L-Four
    Nov 14, 2016 at 11:09
16

Keeping the mapping logic inside of your entity means that your Domain Object is now aware of an "implementation detail" that it doesn't need to know about. Generally, a DTO is your gateway to the outside world (either from an incoming request or via a read from an external service/database). Since the entity is part of your Business Logic, it's probably best to keep those details outside of the entity.

Keeping the mapping somewhere else would be the only alternative - but where should it go? I've tried introducing mapping objects/services but it seemed like overengineering (and probably was) after all was said and done. I've had some success using Automapper and such for smaller projects but tools like Automapper come with their own pitfalls. I've had some pretty hard-to-find issues related to mappings because Automapper's mappings are implicit and completely decoupled from the rest of your code (not like "separation of concerns" but more like a "where does the godforsaken mapping live") so they can sometimes be hard to track down. Not to say that Automapper doesn't have its uses, because it does. I just think mapping should be something that is as obvious and transparent as possible to avoid issues.

Instead of creating a mapping service layer, I've had a lot of success keeping my mappings inside of my DTOs. Since DTOs always sit at the boundary of the application, they can be made aware of the Business Object and figure out how to map from/to them. Even when the number of mappings scales to a large amount it works cleanly. All the mappings are in one place and you don't have to manage a bunch of mapping services inside your Data Layer, Anticorruption Layer, or Presentation Layer. Instead, the mapping is just an implementation detail delegated to the DTO involved with the request/response. Since serializers generally only serialize properties and fields when sending it across the wire, you shouldn't run into any issues. Personally, I've found this the cleanest option and I can say, in my experience, it scales nicely on a large code base.

If the amount of mappings scales to an unreasonable amount (which has yet to happen to me in over 10 years) then you can always create a mapping class that lives close to your DTOs.

1
  • 2
    It's worth noting that since this post, it has happened to me where a DTO got too large (because it was a massive object being stored in a document DB). In this case, I did opt for introducing a class whose sole responsibility was mapping between my business object and my DTO and vice versa. I put this class right alongside the DTO keeping it simple. Personally, I think the choice of avoiding AutoMapper was the right one.
    – Kyle Goode
    May 26, 2023 at 12:22
7

We use T4 templates to create the mapping classes.

Pro's - human readable code available at compile time, faster than a runtime mapper. 100% control over the code (can use partial methods/template pattern to extend functionality on an ad-hoc basis)

Con's - excluding certain properties, collections of domain objects etc., learning T4 syntax.

5

How do you see to implement a constructor inside the DTO class that takes as a parameter a domain object?

Say... Something like this

class DTO {

     // attributes 

     public DTO (DomainObject domainObject) {
          this.prop = domainObject.getProp();
     }

     // methods
}
7
  • 12
    Please, never do this. You do not want your DTO layer to be aware of or dependant on your domain layer. The advantage of mapping is that lower layers can easily be switched out by changing the mapping, or that modifications in the lower layer can be controler by changing the mapping. Let's say dtoA maps to domainObjectA today, but tomorrow the requirement is that it maps to domainObjectB. In your case you have to modify the DTO object, which is a big no-no. You've lost alot of benefits of the mapper. Jul 3, 2014 at 19:23
  • 3
    First at all, thanks! :D. So @FrederikPrijck by inserting a layer between the DTO and the DomainObject, we basically strive this problem of the DTO depends on the domain object , so all the "building work" is done in a middle layer (class) called mapper, that is dependent of both DTOs and DomainObjects. So that is best, or generally recommend, approach to this matter? I only ask to make sure that the point was understood.
    – Victor
    Jul 4, 2014 at 14:58
  • 4
    Yep, the layer is called "Assembler". By using a 3th layer to define the mappings you allow the possibility to easily replace the assembler layer by another implementation (e.g: remove Automapper and use manual mappings), which is always a better choice. The best way to understand it is to think of where I would give you Object A, and someone else gives you Object B. You have no access to each of those objects (only dll), so mapping can only be done by creating a 3th layer. But even if you can access any of the objects, mappings should always be done outside, since they are not related. Jul 4, 2014 at 18:13
  • 6
    Actually, I like this approach, currently I use constructor to map entity to DTO, and use a mapper class to map input dto to entity.
    – dream83619
    Jul 20, 2017 at 4:34
  • 4
    I also like this approach and use it in both ways: constructors to map entity to DTO, and methods (e.g. toNewMyEntity()) for the other way around. Personally I don't think that lower layers can easily be switched out by changing the mapping is a big advantage and don't justify the extra complexity. As well explained in the other answer, having all the mappings in one place is very convenient. Oct 7, 2020 at 8:57
1

Another possible solution: http://glue.codeplex.com.

Features:

  • Bidirectional mapping
  • Automatic mapping
  • Mapping between different types
  • Nested mapping and Flattening
  • Lists and Arrays
  • Verification of relations
  • Testing the mapping
  • Properties, Fields and Methods
0

You can also try Otis, an Object-to-object mapper. Concepts are similar to NHibernate mapping (attribute or XML).

http://code.google.com/p/otis-lib/wiki/GettingStarted

0

I can suggest a tool I created and is open source hosted at CodePlex: EntitiesToDTOs.

Mapping from DTO to Entity and vice-versa is implemented by extension methods, these compose the Assembler side of each end.

You end with code like:

Foo entity = new Foo();
FooDTO dto = entity.ToDTO();
entity = dto.ToEntity();

List<Foo> entityList = new List<Foo>();
List<FooDTO> dtoList = entityList.ToDTOs();
entityList = dtoList.ToEntities();
3
  • 1
    this is architecturally wrong because you make DTO and domain entities aware of each other.
    – Raffaeu
    Dec 11, 2012 at 8:15
  • 5
    @Raffaeu I don't think so since ToDTO/ToDTOs/ToEntity/ToEntities methods are defined as extension methods who represents the Assemblers. The logic of converting an Entity to a DTO and vice-versa is in the extension methods (Assemblers), not in the Entity/DTO in fact.
    – kzfabi
    Dec 11, 2012 at 19:00
  • 4
    If you talk about "Assembler", then implement them in a correct way. Make them modular, make them easility swappable, use dependency injection. There is no need for the domain model itself to be aware of a conversion to DTO. Let's say I have 1 domain object but 50 different applications using the same domain, each having it's own DTO. You are not going to create 50 extensions. Instead you will create one application service for each application with the neccesary assembler(s) being injected as a dependency into the service. Jul 3, 2014 at 19:26
0

Another option would be to use ModelProjector. It supports all possible scenarios and is very easy to use with minimal footprint.

0

We can use Factory, Memento, and Builder pattern for that. Factory hide the details on how to create instance of domain model from DTO. Memento will take care the serialization/deserialization of the domain model to/from DTO and can even access private members. The Builder will allows mapping from DTO to domain with fluent interface.

0

I know this is an old article, and not sure if this is helpful, but I created an Extension Method for doing the mappings called ToDto();

namespace Project.Domain.Extensions
{
    /// <summary>
    /// Extension Methods for Mapping Entities to Domain Objects: See the discussion her on stack overflow regarding best practices.
    /// https://stackoverflow.com/questions/678217/best-practices-for-mapping-dto-to-domain-object
    /// </summary>
    public static class BranchMapperExtensions
    {

        public static IEnumerable<BranchDto> ToDto(this IEnumerable<Branch> branches)
        {
            foreach (Branch b in branches)
                yield return b.ToDto();
        }

        public static BranchDto ToDto(this Branch branch)
        {
            if (branch is null)
                return new BranchDto();

            return new BranchDto()
            {
                Code = branch.Code,
                Name = branch.Name,
                Region = branch.Region.ToDto(),
                Office = branch.Office.ToDto(),
            };
        }
    }
}

Usage:

[HttpGet("")]
        [MapToApiVersion("1.0")]
        public async Task<IEnumerable<BranchDto>> Get()
        {            
            _logger.LogInfo("{0} BranchesController.Get => {1}", DateTime.Now, HttpContext.GetUsername());

            return (await _repository.Branch.GetActiveBranchesAsync()).ToDto();
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.