Domain Driven Design – When to Map a DTO Back to Its Entity?

domain-driven-designdto

From what I've read and implemented, DTO is the object that hold a subset of value from a Data model, in most cases these are immutable objects.

What about the case where I need to pass either new value or changes back to the database?

Should I work directly with the data model/actual entity from my DAL in my Presentation layer?

Or should I create a DTO that can be passed from the presentation layer to the business layer then convert it to an entity, then be updated in the DB via an ORM call. Is this writing too much code? I'm assuming that this is needed if the presentation layer has no concept of the data model. If we are going with this approach, should I fetch the object again at the BLL layer before committing the change?

Best Answer

If you have an entity as in a DDD-entity (not what is generally called an entity in frameworks such as entity framework) then the entity should protect its invariants. Thus using the entity as a DTO is most likely wrong. A DTO is unvalidated input data from the user and should be treated as such. An entity is validated data in one of the object types valid invariants. Thus you should have a conversion between a DTO and an entity that converts a validated DTO to a domain entity object.

In many cases people skimp on these by using anemic domain models (http://www.martinfowler.com/bliki/AnemicDomainModel.html) where the "entities" generally contain no logic and then they put all the invariant protection logic etc in external code (and thus need to check invariants all over the place). This can work, but imho it leads to bugs. But it's something that happens pretty much everywhere - especially since a lot of frameworks encourage this by making it super easy to write code this way. This is imho too bad since it leads to the easiest/fastest way of coding not being the one that leads to the best results (if you follow DDD that is)...

But it's also important to recognise that in many cases DDD might be overkill. If you are basically making a CRUD application (which in many cases you probably are) then DDD might be overkill for your domain. Of course this doesn't mean that you should throw away all the good ideas and just go into full-on "do-anything mode", but in some cases not caring about certain parts of DDD can be the correct choice to make. The hard trick here is, of course, to identify if your domain is complex enough to warrant DDD or if it's easy enough to not bite yourself in the ass by foregoing certain parts of it. :)

Related Topic