简体   繁体   中英

Automapper doesn't fill destination object

I use Automapper with CreateMissingTypeMaps option set to 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?

For some reasons, this is an expected behaviour https://github.com/AutoMapper/AutoMapper/issues/2129 . CreateMissingTypeMaps is not supported for mapping to the same type. The only way to get it work is to configure the mapping explicitly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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