新版本的Automapper在定义子类型映射时会抛出强制类型转换异常

本文关键字:异常 类型转换 映射 Automapper 定义 类型 新版本 | 更新日期: 2023-09-27 18:12:23

假设我有一个源类和两个目标类,一个更通用,一个更特定(从更通用的继承):

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; }
}

For 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中的代码:

  • 3.3.1版本:https://dotnetfiddle.net/6K9PtK
  • 4.0.4版本:https://dotnetfiddle.net/0mF8y8

新版本的Automapper在定义子类型映射时会抛出强制类型转换异常

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