This question already has an answer here:
-
Automapper: Update property values without creating a new object
3 answers
Is there any way to use Automapper 5.1.1 to update an existing object as opposed to creating a new one.
For example we have a Customer
entity and a CustomerViewModel
. We would like to update an existing Customer
with the CustomerViewModel
field values.
Would greatly appreciate your assistance.
It is not adviced to use Automapper to map a model to your Entity. Dependencies or Informations can be overwritten if it isn't used wisely.
But to use it as you want, you only need to create a map from your Model to your Entity and then call
Mapper.Map(myModel, myEntity);
The mapping to entity Problem
I guess you use a ORM like NHibernate or EF, then your Entites are Proxies, where references are proxies too and so on. Now lets imagine you have an ASP.NET MVC Project and you map your Entity to your ViewModel. You show your Model in your View as a form, but you only show the properties that you need in your view, not all that are set in your ViewModel. Then the user sends the Form back to you and your Controller gets the ViewModel back, but this time not all Properties are set, because your View only knew the ones that were shown. If you map your ViewModel back to your entity, all unitialized properties are in there default state and will overwrite the valid data f rom your entity.
Another Problem is, that AutoMapper uses Reflections to set the Properties. Normally the right to exist for an ORM is the possibility to easy implement an DomainLayer. The DomainLayer has some Validations, Calculation... on the Entity itself. If now the Properties set with Reflection it would ignore the Business logic and no Validation, Calculations.... would be executed.
So my advice is, Don't map to Entities ;)