310

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

4

3 回答 3

530

使用采用现有目的地的重载:

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

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

于 2010-03-04T00:34:39.347 回答
29

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

于 2014-04-12T12:53:26.180 回答
9

如果您希望使用 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它共享的所有属性值进行更新。其独特属性的值将保持不变。

这是相关的源代码

于 2018-06-26T18:12:53.383 回答