The case for two-way mapping in AutoMapper

I’m getting more and more requests around the area of two-way mapping, meaning you’d do something like:

Product –> ProductDTO

ProductDTO –> Product

Product being an entity, I can’t for the life of me understand why I’d want to dump a DTO straight back in to a model object.  To get some understanding of how we use AutoMapper, we have:

  • 1500 individual mapping definitions
  • 75 custom value resolvers
  • 38 custom value formatters
  • 5 individual profiles

So what are we using AutoMapper for?  Our five profiles include:

  • From Domain to ViewModel (strongly-typed view models for MVC)
  • From Domain to EditModel (strongly-typed view models for forms in MVC)
  • From EditModel to CommandMessages – going from the loosely-typed EditModel to strongly-typed, broken out messages.  A single EditModel might generate a half-dozen messages.
  • From Domain to ReportModel – strongly-typed Telerik reports
  • From Domain to EDI Model – flattened models used to generate EDI reports

There is no two-way mapping because we never need two-way mapping.  There was a point very early on where we were at a critical junction, and could decide to do two-way mapping.  But we didn’t.  Why?  Because then our mapping layer would influence our domain model.  I strongly believe in POCOs, and a very writeable domain model meant that POCOs were out.  What exactly would two-way mapping do to our domain layer?

  • Force mutable, public collection , like “public EntitySet<Category> Categories { get; }” <- NO.
  • Make testing much, much harder, as we only ever wanted to update a portion of a domain model
  • Force our domain model to be mutable everywhere

So my question to those wanting two-way mapping:

  • What scenarios are you looking at doing two-way mapping?
  • What impact would two-way mapping have on the originating source type?
  • How would you test two-way mappings?

I think using AutoMapper because you don’t want to use the “=” operator is a bit lazy.  Instead, we use it to flatten and reshape, optimizing for the destination type’s environment.  Remember, my original motivation for AutoMapper was:

  • Enable protecting the domain layer from other layers by mapping to DTOs
  • Enable easy testing of the mappings, which would otherwise prevent us from creating the mapping in the first place

So…why two-way mapping?

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in AutoMapper. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Gagan Rajpal

    One scenario where a two way mapping could be useful would be domain model to dto which gets passed through a web service and then dto to domain model. you may not necessarily want to pass the domain model thru the web service to reduce overhead, or due to serialization issues.

    Gagan

  • Gagan Rajpal

    to be more specific, its not necessarily a two way mapping, but rather a
    source domain model to dto, this dto is exposed thru a web service then dto to target domain model,,,, the source and target domain model need not necessarily be exactly the same.

  • http://vijay.screamingpens.com Vijay Santhanam

    I don’t particularly mind two way mapping being separate, but with MS MVC I do have alot of EditModels that are converted from DomainModels (for edit forms) and back again (when save is pressed).

  • http://igorbrejc.net Igor Brejc

    We have an “external” domain model generated from Web service data contract, but it doesn’t fit our needs internally (for MVC), so we implemented our own. But we still need two-way mapping between those two models (for Web service’s input and output parameters)

  • Jeff Lembke

    Thanks for this. We’d wanted to do mapping to Domain objects and created the very tension you are talking about. This helped clear up my thinking.

  • http://pabloblamirez.blogspot.com Paul Blamire

    Hi Jimmy,

    Have you blogged about how you convert the EditModel to CommandMessages before? I don’t remember that, and a search for CommandMessages doesn’t return anything.

    I’d be very interested to learn a little more about some of the specifics, just to see how the alpha devs route information back from form to model (not viewmodel). Obviously I initially just thought you were creating the message to pass into the service layer to perform the form operation, the fact you said you may produce many commands though made me wonder if there was more to it?

    I suspect this is where you neatly sidestep any perceived requirement for 2 way mapping.

    Loving all the automapper posts, great work :-)

  • http://blog.zoolutions.se Mikael Henriksson

    I use Automapper one way only. Mostly used it when I am too lazy and need to copy one entity to another entity straight off but it would be extremely usefull for ASP.NET MVC as well. Never had any use for any two way copying.

  • Klenne

    We have a domain model that we map to DTO objects requested by the client application. At the client layer these DTO objects are used to display/edit info. When such a DTO is received at our backend service, we map it to a domain model again. Sometimes straightforward mapping is not possible, sometimes it is. That’s when 2 way mapping comes into play. How are you mapping incoming DTO to your domain model?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Klenne

    Incoming DTOs are mapped to command messages, which are handled individually. Sometimes this results in modifying the domain, sometimes not. It’s not always the same, and it’s never as simple as going from domain -> DTO, which is why we ditched trying.

  • Jan Ove Skogheim Olsen

    The need for two-way mapping comes from people doing basic data driven CRUD operations through their service layers. So instead of fixing the real problem of not doing so, they want AutoMapper to save them from the trouble of having to do the mapping manually. The fact that AutoMapper don’t support this is a good thing, as it enforces a good design principle of not exposing CRUD. Those who still desperately want to do it, can already do so by just setting up the mapping each way separately anyway.

  • Paul Sanchez

    I believe Olsen is pretty accurate. People are designing their domain to be directly mapped to and from the presentation layer. I used to do that until I started looking into command messages and realized that this is the better way to go. Even if I did want to map to and from a presentation model, the mapping logic would be different in each direction.

    I wouldn’t even know how the AutoMapper API should be written to handle such a scenario. Before hitting this thread, I just set up the mapping each way separately.

    Part of the documentation of AutoMapper should probably state the design patterns it is expected to be used within.

  • http://www.patrickgannon.net Pat Gannon

    2-way mapping would be very handy for us here at HSI. We have AutoMapper.CreateMap and then AutoMapper.CreateMap all over the place.

    To answer your questions…

    * What scenarios are you looking at doing two-way mapping?

    Mapping DTOs to entities and then entities back to DTOs. For one example, we have a workflow application that gets data from a web service (which comes from a DB by way of entities and NH). The user can then make changes in the app, publish the contracts back to the web service (which puts them back in the DB by way of entities and NH).

    * What impact would two-way mapping have on the originating source type?

    None. For simple entities where the only sensible DTO shape looks exactly like the entity, 2-way mapping would be very handy. (This is common.) For more complex entities where the DTO would make more sense having a different shape than the entity, then you could have separate mappings for DTO -> Entity and Entity -> DTO to re-shape the data according to your needs.

    * How would you test two-way mappings?

    Test the translation of a DTO to entity and then separately test the translation of an entity to a DTO (or what have you).

  • http://xml-guy.com/blog Hoghweed

    I’m interested in a practical example of what you mean about “not needing a two way binding”.
    This because if I think about mapping a Model POCO to a ViewModel then after MVC model binding, I want to remap some part of my ViewModel to a Model Object just because I use it as an input of our service methods, and I’m courios about how you have implemented what you said

  • Alex G.

    Can someone explain further the concept of command messages and include a sample using automapper? It might be helpful for those of us who do not understand the concepts behind it and why it might be useful over a DTO->entity mapping.

  • http://shouldersofgiants.co.uk/blog Piers

    I’d like to put forward an argument for 2 way mapping… that might just illustrate my lack of ability to see the wood for the trees, but here goes:

    Olsen, above, was indicating that performing CRUD throughout an application stack was a bad smell, but looking at REST based services, that can be what 80% of the functionality needs to do. However, its not straight CRUD… for instance, if a client does a GET on a resource, the representation they recieve probably won’t be a straight serialisation of an entity object. You’ll probably want to add some data (e.g. the resource’s URI and URIs of related resources). YOu might want to hide some data (e.g. confidential data like total number of sales of a product). These all seem good reasons to have a DTO and to introduce AutoMapper.

    But what about when the client PUT or POSTs the representation back… it will be in the same form that the DTO was served to them. So probably the simplest type to deserialise that representation into is the DTO that was used for the GET processing. What next in this “CRUD” process?

    Without two way mapping it appears I have two choices:

    1) Hand crank the code to retrieve the entity from the database and change some of its values to match those passed in by the client, the save. This seems a shame since I’m only doing the reverse of what AutoMapper did automatically for me (i.e. AutoMapper has been fantastic for half of my functionality). This could work for a simple service, but as the service has to support more representations of the same entity, the amount of code would really build up.

    2) As suggested by other commentors, have two separate mappings Entity -> DTO and DTO -> Entity… but, hang on, the DTO -> Entity mapping won’t pass validation because the DTO doesn’t have enough properties to populate the entire Entity. Remember, the confidential data mentioned above is not available in the DTO.

    Neither of these is satisfactory. My ideal would be a single Entity -> DTO mapping that was capable of merging a DTO back into an existing Entity (i.e. it only updated the fields in the Entity that the mapping was populating in the opposite direction).

    So does this count as a viable reason? Or am I missing an obvious alternative?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Piers

    One thing to look at is to see how other MVC frameworks solve this problem. For example, do Rails folks use DTOs? If not, what is built into Rails that solves the screen/entity divide?

    For me personally, if I didn’t _have_ to use AutoMapper, I wouldn’t. If a screen is editing an entity, and I could somehow make model binding work that it wouldn’t screw everything up, I would. Otherwise, it’s an extra layer that I might not need.

    I’m going to chat with some Rails folks and see what they’re doing, and maybe that will answer the larger question.

  • Nick Y

    Jimmy, I’d like to explore the Command Message route, but I haven’t been able to find any blogs/articles about it.

    The CodeCampServer and Tarantino RulesEngine are all I’ve been able to find – is this the best place to learn about the pattern? Any other guidance would be much appreciated.

  • http://www.lucisferre.net Chris Nicola

    Another benefit to using a CommandMessage is the ability to handle them asynchronously or treat them as events using an EventAggregator to allow different services to subscribe to them.

  • Jonathan Tew

    Thanks, good article. I’d been wondering why there wasn’t any consideration for 2-way in AutoMapper but it makes sense now.

  • http://www.krokonoster.com Krokokonoster

    I can’t see how I would go without mapping viewmodels to domain models.
    Example: Got a “Registration” Domain model in the relevant layer, used by my service to create a registration.
    Got a “Registration” View Model used by the view (same properties as domain model, will lists, validations and so on).
    So…render the view using the “Registration” View Model.
    Post action check if it’s valid, if so, convert it to a “Registration” Domain Model and pass that to the registration service.

    This is the simplest example, but fact is I’m doing it all over the place.

    Jim, you did a great job on AutoMapper, but it’s obvious…two-way mapping will just have to be part of the whole thing to make sense (And reading the above comments, I’m sure I’m not alone thinking so)

  • Nima

    What about WCF, When UI send back DTO to domain and need for build entity from DTO?

  • DanO

    Jimmy,

    Could you post an example of the command message pattern you use for mapping strongly-typed MVC EditModels to command messages? I am using EF v4 and the POCO generator, and my POCO entities are in a separate project from data repositories. I am trying to figure a good way to transform my EditModel (posted from a form) into actual entity / data updates.

    In particular, I’d love to see an example where the EditModel contains at least one collection of child objects, rather than simple value-type properties.

    Thanks, Dan

    • http://twitter.com/VishalRJoshi Vishal Joshi

      I am trying to do something very similar to what DanO mentioned.
      Thanks
      Vishal

  • David Pickering

    Hi Jimmy, 

  • David Pickering

    Hi Jimmy,

    I’m fairly new to AutoMapper, and perhaps I’m thinking about the particular problem I’m working the wrong way, but here’s my requirement for two-way mapping. 

    I’ve got a WCF Service Library where I’m using the ACORD Life Insurance standard’s XSDs to generate my Service, Message & Data Contracts (using the Web Service Software Factory). These services talk to various back-end LOB systems and are meant to be exposed to external parties in B2B scenarios, and also used by internal applications. 

    I’m currently building a Domain Model class library and Service Helper class library for consumption by the internal apps, aiming to simplify the way they communicated with these fairly ugly ACORD based message contracts, because talking direct to the ACORD services is not a pleasant experience.

    The Service Helpers will expose simple methods like “UpdateParty(Party party)”, where the Party object passed in is a nice clean Domain Model POCO.  I want to map the Domain Model Party POCO to my ugly ACORD Party data contract, to be sent in a request message to the relevant ACORD service operation. 

    Another method will be “Party GetParty(string id)”. In this case I’m going to get back an ACORD Party Data Contract from my ACORD service operation, and then I want to map that back to the Domain Model Party object to pass back to the Service Helper consumer.

    Therefore, I feel I need two way mapping to map back and forth between my Domain Model and ACORD based Data Contracts.

    Am I barking up the wrong tree?

    Cheers,
    David

    • Anonymous

      Would you mind re-posting this on the automapper mailing list? The
      discussion might be valuable that others might want to chime in. Thanks!

      • David Pickering

        Sure, have re-posted to the mailing list. See: http://groups.google.com/group/automapper-users/browse_thread/thread/b89090d21cb7c4fe

  • Acaz Souza Pereira

    Hi Jimmy, I’m using ViewModels with .Net MVC, I pass my Entities to ViewModels using AutoMapper, that’s ok, so I’m getting from ViewModels to pass to Entities too. That’s my scenario. Is a Two way mapping, what’s solution to that?

    • Ignacio Fuentes

      it really is hard finding some good samples on how in the world you are supposed to handle the editmodel after it came back  to actually populate a entity.

  • Jag

    As someone new to MVC, I believe this usage is the source of confusion:

    “From EditModel to CommandMessages – going from the loosely-typed EditModel to strongly-typed, broken out messages.  A single EditModel might generate a half-dozen messages.”

    In short, I think there’s a false expectation that Edit Models are mapped back to Domain Models. It’s clear that this is not the case, and that you use CommandMessages, which brings us to a second point of confusion. What are CommandMessages?

    I imagine there’s sample code that demonstrates a good way to take an EditModel and apply the necessary changes to your Domain Model.

    • Anonymous

      Yeah, I think you’re right. We used to have a code sample, but the context was so simplified that it didn’t make sense that the pattern was even used. I’ll see if I can dig something up.

      • Adam Tuliper

        Hi Jimmy – Did you ever dig anything up here? I have to agree with Jag here. We all know AutoMapper is commonly used to go from Entity->ViewModel. Logic would then say it has nothing to do with laziness, but cleaner controllers to map our properties back to an entity. This fits well with say Entity Framework as we can load up an entity, merge its properties, mark it as modified (since AutoMappers changes dont get picked up by the context) and save it, all with minimal code. Why would this not be a case for usage of a field mapper?  Ok, I guess we could write smart templates to script this out, but if we’re already going ‘one way’ why not back the other? The pattern you’ve discussed with MVC I have yet to see, so I’m curious of some examples. Thanks!!

    • http://www.reddnet.net Stephen M. Redd

      The whole CommandMessage thing threw me off a lot… so I did some digging… lots of digging. 

      If I’m correct though, and I might not be, what Jimmy was talking about is a pattern that is very similar to what CodeCameServer uses, which involves the  MVCContrib.CommandProcessor.     

      I’m still digging through the details, but generally it looks like all updates are done via calls to a rules engine. You give it a message object, and the rules engine can tell from the message object’s type which command it needs to run.

      Setting up the rules engine involves creating custom classes that define the command, a class to define the rules to apply, classes for any custom rules, and a class that defines the actual message that will be passed around…. an outright obscene number of classes actually. 

      It seems to be overkill times about a million, and I cannot justify this level of complexity in an app the size of CodeCampeServer. It would seem like a simple transaction script design  pattern would probably have done just fine, and been a lot smaller and easier to maintain. Maybe a rules engine like this makes sense given different requirements, or at a much larger scale (though I’d have to see details to agree).

      Still though, the general idea is that the domain would expose very narrowly defined operations/commands for any writes to the DB. When you called those operations/command, you would not be passing in whole entity objects as parameters. Instead, you would pass in objects that are designed specifically for the operation/command being invoked, and back-end domain would then make or modify the appropriate entity objects.  

      The command message pattern makes the assumption that only the back-end domain will instantiate or modify the real entities. The front end can read them, but would never change one.

      This is not the dominant pattern used in asp.net MVC, at least not that I’ve seen. Many MVC apps use  entity objects as both input and output to the back-end; and this is especially true when using EF code-first or POCOs. Most of the books, code samples, templates, and scaffolders also use the back-end entity types bidirectionally; even when view models are being used as intermediaries.

  • Diego H. Bustamante

    I’m in agreement that you shouldn’t map a DTO or Model (from mvc) back into an Entity… however, I’m using the mapping in order to generate query builder (entity sql) statements from my models (implemented in jqGrid  [Lib.Web.MVC]) that can execute in my DAL againsts Entities… of course if i was a LINQ Expressions pro, I’d circumvent this altogether, yet i’d still need some sort of mapping.

  • http://twitter.com/ehdv Ted Driggs

    What then is the recommended way to take in an edit model and save it back to the database? Currently I validate the incoming edit model, then once the data it contains is known to be good I want to convert it to an entity and save it as painlessly as possible (it’s not out of the question that the schema of these objects may change later, so a solution like AutoMapper would be better than hand-writing the constructor for the entity.

    • Anonymous

      You can certainly use AutoMapper if you like – it just doesn’t work well for collection types (nothing really does), nor do you want to change your entity to better support this behavior. Try it out, and if things get weird/difficult, just do it manually.

      • http://twitter.com/ehdv Ted Driggs

        On further examination, I think you’re right not to support it – there shouldn’t be enough places where the EditModel to Entity conversion is taking place to make the mapping worthwhile. 

        For now I’ve refactored that conversion process out into a method in the entity’s controller which also validates the EditModel. Not sure if this is a great idea, but I need to do validation that can’t be expressed in data annotations and this ensures only valid EditModels ever even become entities.

  • Pingback: Domain model to ViewModel and back again using repository pattern and Entity Framework in MVC3 | PHP Developer Resource

  • Pingback: How to mutate editmodel/postmodel to domain model

  • Saulo Vallory

    Maybe I’m missing the point here. I don’t know. I’m using “two-way” mapping by creating two mapping configurations (Entity => DTO and DTO => Entity). They have different rules and I set up AutoMapper to ignore the already existing related entities, while setting their ids to my exposed foreign key. I’m even mapping a comma separated list of words to a Tag collection, since in my schema tags aren’t reused even when they have the same name.

    Look at my mapping code…

    Mapper.CreateMap() .ForMember(d => d.Tags, opt => opt.MapFrom(d => d.Tags.Aggregate(“”, (total, tag) => total + (tag.Name + “, “)).Trim(‘ ‘,’,')));
    Mapper.CreateMap() .ForMember(d => d.Competition, opt => opt.Ignore()) .ForMember(d => d.Tags, opt => opt.MapFrom(d => d.Tags.Split(‘,’).Select(name => new Tag() { Name = name.Trim() })));

    gist: https://gist.github.com/3650672

    See, a design is submitted to a competition, so the competition already exists. If I allow
    AutoMapper to map the competition property, EF would try to insert a new Competition,
    so I have to ignore it and only set the foreign key. Of course, I have validation on the
    DTO and on my Entity.

    Is there anything wrong with this approach?

  • Pingback: How to use AutoMapper properly? | helicoder

  • schneidr

    People _desperately_ want tools for mapping and transformation.

    AutoMapper is a high profile, high quality product, and it’s name implies it does mapping. So people try it and get confused/frustrated as soon as they want to do something that AutoMapper, an opinionated tool, was never designed to do.

    Two way mapping is perfectly legitimate thing to want to do. Patterns books are full of example of mappings happening in a multitude of directions. Mappings and transformation is fundamental to computer science and software patterns.

    For example right now I have a need to map from a spreadsheet which has 3 columns: MyPosition_X, MyPosition_Y, MyPosition_Z and I want to automatically map that into member called MyPosition, which is a vector with 3 properties: X, Y and Z. Very straight forward, and could easily work based on conventions. But I don’t think AutoMapper can do it :(

    That is not to say Jimmy’s approach is wrong. As he states, he built a tool for his own needs. The real issue is the confusion over capability and a general dearth of tools in this market. Personally I’d really like to to see AutoMapper become less opinionated and more general purpose.

    • jbogard

      I accept pull requests :) But seriously, it’s far, far easier to build an opinionated tool than a general purpose-tool. A general-purpose tool is probably something I’d build and charge money for.