Jim*_*ard 420
使用占用现有目标的重载:
Mapper.Map<Source, Destination>(source, destination);
Run Code Online (Sandbox Code Playgroud)
是的,它返回目标对象,但这仅适用于其他一些模糊的场景.这是同一个对象.
小智 15
要完成这项工作,您必须为源和目标类型创建CreateMap,即使它们是相同的类型.这意味着如果你想要
Mapper.Map<User, User>(user1, user2);
你需要像这样创建地图
Mapper.Create<User, User>()
如果您希望使用 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);
Run Code Online (Sandbox Code Playgroud)
dest现在将使用src它共享的所有属性值进行更新。其独特属性的值将保持不变。