定义子类型映射时,新版本的 Automapper 抛出转换异常

New version of Automapper throws cast exception when subtype mapping is defined

假设我有一个源 class 和两个目标 class,一个更通用,一个更具体(继承自更通用的):

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:

在 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);

同样,映射到 DestinationDerived 也能正确映射继承自 base:

的属性
var src = new Source() { a = 1, str = "foo" };
var dest = new DestinationDerived();

Mapper.Map(src, dest);

Console.WriteLine("dest.a: " + dest.a);