Automapper to update an existing object as opposed to creating a new one [duplicate]

烂漫一生 提交于 2019-12-11 05:14:54

问题


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.


回答1:


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 ;)



来源:https://stackoverflow.com/questions/40063492/automapper-to-update-an-existing-object-as-opposed-to-creating-a-new-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!