2

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

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

1 回答 1

3

在 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也正确映射从基础继承的属性:

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

Mapper.Map(src, dest);

Console.WriteLine("dest.a: " + dest.a);
于 2015-09-10T16:25:28.963 回答