C# 定义子类型映射时,Automapper的新版本会引发强制转换异常
假设我有一个源类和两个目标类,一个更一般,一个更具体(从更一般的类继承): 对于Automapper 3.*而言,此代码非常有效:C# 定义子类型映射时,Automapper的新版本会引发强制转换异常,c#,automapper,automapper-4,C#,Automapper,Automapper 4,假设我有一个源类和两个目标类,一个更一般,一个更具体(从更一般的类继承): 对于Automapper 3.*而言,此代码非常有效: Mapper.Initialize(cfg => { cfg.CreateMap<Source, DestinationBase>(); cfg.CreateMap<Source, DestinationDerived>() .IncludeBase<Source,
Mapper.Initialize(cfg => {
cfg.CreateMap<Source, DestinationBase>();
cfg.CreateMap<Source, DestinationDerived>()
.IncludeBase<Source, DestinationBase>();
});
var src = new Source() { A = 1, Str = "foo" };
var dest = new DestinationBase();
Mapper.Map(src, dest);
我有没有做错什么,或者这是AutoMapper中的一个bug
.net fiddle中的代码:
- 3.3.1版本:
- 4.0.4版本:
- 在4.x中,似乎不再需要显式地包含base。以下各项工作正常,并按预期将
a
输出为1
Mapper.Initialize(cfg => {
cfg.CreateMap<Source, DestinationBase>();
cfg.CreateMap<Source, DestinationDerived>();
});
var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationBase();
Mapper.Map(src, dest);
Console.WriteLine("dest.a: " + dest.a);
System.InvalidCastException: Unable to cast object of type 'DestinationBase' to type 'DestinationDerived'
Mapper.Initialize(cfg => {
cfg.CreateMap<Source, DestinationBase>();
cfg.CreateMap<Source, DestinationDerived>();
});
var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationBase();
Mapper.Map(src, dest);
Console.WriteLine("dest.a: " + dest.a);
var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationDerived();
Mapper.Map(src, dest);
Console.WriteLine("dest.a: " + dest.a);