简体   繁体   English

Automapper不会填充目标对象

[英]Automapper doesn't fill destination object

I use Automapper with CreateMissingTypeMaps option set to true . 我用AutomapperCreateMissingTypeMaps设置选项true If I try to fill an existing object of the same type, it doesn't work. 如果我尝试填充相同类型的现有对象,则它不起作用。

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

If I create a new object of the same type, it works fine 如果我创建一个相同类型的新对象,它工作正常

var a3 = mapper.Map<A>(a1); // a3.X is set

If I fill an existing object of a different type, it also works 如果我填充不同类型的现有对象,它也可以

class B
{
    public string X { get; set; }
}

var b = new B();
mapper.Map(a1, b); // b.X is set

But if I try to fill an existing object of the same type, it doesn't. 但是,如果我尝试填充相同类型的现有对象,则不会。 Is it a bug in Automapper or am I missing something? 它是Automapper的错误还是我错过了什么?

For some reasons, this is an expected behaviour https://github.com/AutoMapper/AutoMapper/issues/2129 . 出于某些原因,这是一种预期的行为https://github.com/AutoMapper/AutoMapper/issues/2129 CreateMissingTypeMaps is not supported for mapping to the same type. 映射到相同类型不支持CreateMissingTypeMaps The only way to get it work is to configure the mapping explicitly: 使其工作的唯一方法是显式配置映射:

var config = new MapperConfiguration(cfg => cfg.CreateMap<A, A>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM