自动映射器更新现有对象,而不是创建一个新对象 [英] Automapper to update an existing object as opposed to creating a new one

查看:93
本文介绍了自动映射器更新现有对象,而不是创建一个新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用 Automapper 5.1.1 来更新现有对象,而不是创建一个新对象.

Is there any way to use Automapper 5.1.1 to update an existing object as opposed to creating a new one.

例如,我们有一个Customer实体和一个CustomerViewModel.我们想用CustomerViewModel字段值更新现有的Customer.

For example we have a Customer entity and a CustomerViewModel. We would like to update an existing Customer with the CustomerViewModel field values.

非常感谢您的协助.

推荐答案

不建议使用Automapper将模型映射到您的实体.如果不明智地使用依赖项或信息,则可能会覆盖它们. 但是要使用它,只需创建一个从模型到实体的映射,然后调用

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

到实体问题的映射

我猜您使用了像NHibernate或EF这样的ORM,那么您的实体就是代理,引用也就是代理,依此类推.现在,假设您有一个ASP.NET MVC项目,并且将实体映射到ViewModel.您可以在视图中以窗体形式显示模型,但是仅在视图中显示所需的属性,而不是在ViewModel中设置的所有属性.然后,用户将Form发送回给您,您的Controller取回ViewModel,但这一次并未设置所有的Properties,因为您的View只知道所显示的那些.如果将ViewModel映射回您的实体,则所有单位化属性均处于默认状态,并将覆盖您实体的有效数据.

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.

另一个问题是,AutoMapper使用反射来设置属性.通常,ORM的存在权是轻松实现DomainLayer的可能性. DomainLayer在实体本身上具有一些验证,计算....如果现在使用反射设置了属性,它将忽略业务逻辑,并且不执行任何验证,计算....

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.

所以我的建议是,不要映射到Entities;)

So my advice is, Don't map to Entities ;)

这篇关于自动映射器更新现有对象,而不是创建一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆