views:

158

answers:

1

Many people have written about using Automapper to map domain objects (models) to view models, which I find very interesting and useful, but my question is about how to do the opposite. I understand the complexity of this process and why Automapper doesn't work in that scenario but I have to do that a lot with form posting, specially when updating.

I have a model, I map it to a view model and then I present a form to the user. Then, the form is posted and as models can be quite complex, I use custom ModelBinders to handle the response and building a new model, which won't be directly persisted. Instead, I load the original model from the DB and call a method to update it from the posted from without breaking anything. But this becomes repetitive and maybe there's a better approach.

Examples I've seen are very Model limited and naive, but in our application we may have now 50+ form posting scenarios like this one and growing.

+3  A: 

If you want to go the other direction, first create the map to the other direction, Mapper.Map()

Next, you might want to create type converters (Mapper.CreateMap().ConvertUsing()), as sometimes forms can be more...string-y.

Then, you may need to ignore or use destination values. That can be configured with ForMember(entity => entity.Id, opt => opt.Ignore()) or ForMember(entity => entity.ChildCollection, opt => opt.UseDestinationValue()).

Finally, you'll want to use the overload that takes an existing destination object, Mapper.Map(dto, entity).

Jimmy Bogard
I didn't mean exclusively using Automapper, but thanks for the great response, I'll try this ASAP.
Marc Climent