C# Automapper:在不创建新对象的情况下更新属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2374689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automapper: Update property values without creating a new object
提问by ryudice
How can I use automapper to update the properties values of another object without creating a new one?
如何在不创建新对象的情况下使用 automapper 更新另一个对象的属性值?
采纳答案by Jimmy Bogard
Use the overload that takes the existing destination:
使用采用现有目的地的重载:
Mapper.Map<Source, Destination>(source, destination);
Yes, it returns the destination object, but that's just for some other obscure scenarios. It's the same object.
是的,它返回目标对象,但这仅适用于其他一些晦涩的场景。这是同一个对象。
回答by Flux Xu
To make this work you have to CreateMap for types of source and destination even they are same type.
That means if you want to
Mapper.Map<User, User>(user1, user2);
You need to create map like this
Mapper.Create<User, User>()
要完成这项工作,您必须为源和目标的类型创建映射,即使它们是相同的类型。这意味着如果你想
Mapper.Map<User, User>(user1, user2);
你需要像这样创建地图
Mapper.Create<User, User>()
回答by BobbyA
If you wish to use an instance method of IMapper, rather than the static method used in the accepted answer, you can do the following (tested in AutoMapper 6.2.2
)
如果您希望使用 IMapper 的实例方法,而不是接受的答案中使用的静态方法,您可以执行以下操作(在 中测试AutoMapper 6.2.2
)
IMapper _mapper;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
_mapper = config.CreateMapper();
Source src = new Source
{
//initialize properties
}
Destination dest = new dest
{
//initialize properties
}
_mapper.Map(src, dest);
dest
will now be updated with all the property values from src
that it shared. The values of its unique properties will remain the same.
dest
现在将使用src
它共享的所有属性值进行更新。其独特属性的值将保持不变。