[英]how to map only if destination object doesn't have a value in Automapper
[英]Automapper doesn't fill destination object
我用Automapper
与CreateMissingTypeMaps
设置选项true
。 如果我尝试填充相同类型的现有对象,则它不起作用。
class A
{
public string X { get; set; }
}
var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();
var a1 = new A { X = "sample" };
var a2 = new A();
mapper.Map(a1, a2); // a2.X was not set
如果我创建一个相同类型的新对象,它工作正常
var a3 = mapper.Map<A>(a1); // a3.X is set
如果我填充不同类型的现有对象,它也可以
class B
{
public string X { get; set; }
}
var b = new B();
mapper.Map(a1, b); // b.X is set
但是,如果我尝试填充相同类型的现有对象,则不会。 它是Automapper
的错误还是我错过了什么?
出于某些原因,这是一种预期的行为https://github.com/AutoMapper/AutoMapper/issues/2129 。 映射到相同类型不支持CreateMissingTypeMaps
。 使其工作的唯一方法是显式配置映射:
var config = new MapperConfiguration(cfg => cfg.CreateMap<A, A>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.