简体   繁体   English

如何使用显式成员映射配置AutoMapper for Polymorphism?

[英]How to configure AutoMapper for Polymorphism with explicit member mapping?

Consider the following basic case: 考虑以下基本情况:

Mapper.CreateMap<FromBase, ToBase>()
        .Include<FromD1, ToD1>()
        .Include<FromD2, ToD2>();

Mapper.CreateMap<FromD1, ToD1>()
        .ForMember( m => m.P0, a => a.MapFrom( x => x.Prop0 ) )
        .ForMember( m => m.P1, a => a.MapFrom( x => x.Prop1 ) );

Mapper.CreateMap<FromD2, ToD2>()
        .ForMember( m => m.P0, a => a.MapFrom( x => x.Prop0 ) )
        .ForMember( m => m.P2, a => a.MapFrom( x => x.Prop2 ) );

Mapper.AssertConfigurationIsValid();

FromBase[] froms = {
        new FromD1() { Prop0 = 10, Prop1 = 11 },
        new FromD2() { Prop0 = 20, Prop2 = 22 }
};

var tos = Mapper.Map<FromBase[], ToBase[]>( froms );

With: 附:

public class FromBase {
    public int Prop0 { get; set; }
}
public class FromD1 : FromBase {
    public int Prop1 { get; set; }
}
public class FromD2 : FromBase {
    public int Prop2 { get; set; }
}

public class ToBase {
    public int P0 { get; set; }
}
public class ToD1 : ToBase {
    public int P1 { get; set; }
}
public class ToD2 : ToBase {
    public int P2 { get; set; }
}

It looks like the example on Automapper's doc. 它看起来像Automapper的doc上的例子

However the Mapper.AssertConfigurationIsValid() assertion throws: 但是Mapper.AssertConfigurationIsValid()断言抛出:

AutoMapperConfigurationException: "The following 1 properties on ToBase are not mapped: P0 Add a custom mapping expression, ignore, or rename the property on FromBase." AutoMapperConfigurationException:“未映射ToBase上的以下1个属性:P0在FromBase上添加自定义映射表达式,忽略或重命名该属性。”

Unless I am missing something, the only differences with the example it that I am not relying on conventions, mapping the properties manually with ForMember . 除非我遗漏了一些东西,与示例的唯一区别是我不依赖于约定,使用ForMember手动映射属性。 Also there are several derived classes. 还有几个派生类。 Not sure how these would be a problem, but I can't think of anything else. 不知道这些会是怎么回事,但我想不出别的什么。

Any idea? 任何想法?

虽然配置验证断言失败,但映射实际上工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM