[英]automapper - map properties with values
I have two objects, which are basically (so not entirely!) the same. 我有两个对象,它们基本上(因此不完全相同)是相同的。 They both have properties with values.
它们都具有带有值的属性。
I'd like to map one object to the other and overwrite all the property values of the from the source target to the destination target. 我想将一个对象映射到另一个对象,并覆盖从源目标到目标目标的所有属性值。 But it seems that this isn't happening by default?
但是看来这不是默认情况下发生的吗?
NOTE: My maps are already defined at the startup of my application. 注意:我的地图已经在我的应用程序启动时定义。
My objects basically looks like this: 我的对象基本上如下所示:
public class Object1
{
public String Name = "My new Name";
}
public class Object2
{
public String Name = "My old Name";
}
// Then somewhere in my code:
Mapper.Map(obj1, obj2);
So i try to map all the values from Object1
, to Object2
. 所以我尝试将所有值从
Object1
映射到Object2
。 But when the mapping is done, then Object2
still has its old value, instead of the value from Object1
. 但是,当映射完成后,
Object2
仍然具有其旧值,而不是Object1
中的值。
How can i map the values in AutoMapper? 如何在AutoMapper中映射值?
You should configure AutoMapper
first: 您应该首先配置
AutoMapper
:
Mapper.CreateMap<Object1, Object2>();
In your example you are trying to map classes
but its impossible, you should map instances
of the classes: 在您的示例中,您尝试映射
classes
但是这不可能,您应该映射类的instances
:
var o1 = new Object1();
var o2 = new Object2();
Mapper.Map(o1, o2);
Update 更新资料
Automapper
returns new instance, assign that return instance to the old one. Automapper
返回新实例,并将该返回实例分配给旧实例。
object1 = Mapper.Map<Object1, Object2>(object2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.