假设我有一个源类和两个目标类,一个更通用,一个更具体(继承自更通用的一个):
public class Source
{
public int A { get; set; }
public string Str { get; set; }
}
public class DestinationBase
{
public int A { get; set; }
}
public class DestinationDerived : DestinationBase
{
public string Str { get; set; }
}
对于 Automapper 3.*,此代码运行良好:
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);
但是,升级到 4.0.4 后,此映射会引发异常:
System.InvalidCastException: Unable to cast object of type 'DestinationBase' to type 'DestinationDerived'
我做错了什么还是AutoMapper中的错误?
.net fiddle 中的代码:
- 3.3.1版本:https ://dotnetfiddle.net/6K9PtK
- 4.0.4版本:https ://dotnetfiddle.net/0mF8y8