How to configure AutoMapper for Polymorphism with explicit member mapping?

自闭症网瘾萝莉.ら 提交于 2019-12-19 08:04:33

问题


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.

However the Mapper.AssertConfigurationIsValid() assertion throws:

AutoMapperConfigurationException: "The following 1 properties on ToBase are not mapped: P0 Add a custom mapping expression, ignore, or rename the property on 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. Also there are several derived classes. Not sure how these would be a problem, but I can't think of anything else.

Any idea?


回答1:


The mapping actually works fine, although the configuration validation assertion fails...



来源:https://stackoverflow.com/questions/4456519/how-to-configure-automapper-for-polymorphism-with-explicit-member-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!