自动映射:更新属性值而不创建新对象

时间:2010-03-03 20:28:57

标签: c# .net automapper

如何使用automapper更新另一个对象的属性值而不创建新对象?

3 个答案:

答案 0 :(得分:386)

使用占用现有目标的重载:

Mapper.Map<Source, Destination>(source, destination);

是的,它会返回目标对象,但这仅适用于其他一些不明显的场景。这是同一个目标。

答案 1 :(得分:14)

要完成这项工作,您必须为源和目标类型创建CreateMap,即使它们是相同的类型。 这意味着如果你想 Mapper.Map<User, User>(user1, user2); 你需要像这样创建地图 Mapper.Create<User, User>()

答案 2 :(得分:0)

如果您希望使用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现在将使用其共享的src中的所有属性值进行更新。其唯一属性的值将保持不变。

Here's the relevant source code