假设我有一个源类:
public class Source
{
//Several properties that can be mapped to DerivedBase and its subclasses
}
还有一些目的地类别:
public class DestinationBase
{
//Several properties
}
public class DestinationDerived1 : DestinationBase
{
//Several properties
}
public class DestinationDerived2 : DestinationBase
{
//Several properties
}
然后我希望派生的目标类继承基类的自动映射器配置,因为我不想重复它,有没有办法实现这一点?
Mapper.CreateMap<Source, DestinationBase>()
.ForMember(...)
// Many more specific configurations that should not have to be repeated for the derived classes
.ForMember(...);
Mapper.CreateMap<Source, DestinationDerived1 >()
.ForMember(...);
Mapper.CreateMap<Source, DestinationDerived2 >()
.ForMember(...);
当我这样写它时,它根本不使用基本映射,并且 include 似乎对我没有帮助。
编辑:这就是我得到的:
public class Source
{
public string Test { get; set; }
public string Test2 { get; set; }
}
public class DestinationBase
{
public string Test3 { get; set; }
}
public class DestinationDerived1 : DestinationBase
{
public string Test4 { get; set; }
}
public class DestinationDerived2 : DestinationBase
{
public string Test5 { get; set; }
}
Mapper.CreateMap<Source, DestinationBase>()
.ForMember(d => d.Test3, e => e.MapFrom(s => s.Test))
.Include<Source, DestinationDerived1>()
.Include<Source, DestinationDerived2>();
Mapper.CreateMap<Source, DestinationDerived1>()
.ForMember(d => d.Test4, e => e.MapFrom(s => s.Test2));
Mapper.CreateMap<Source, DestinationDerived2>()
.ForMember(d => d.Test5, e => e.MapFrom(s => s.Test2));
AutoMapper.AutoMapperConfigurationException :找到未映射的成员。查看下面的类型和成员。
添加自定义映射表达式、忽略、添加自定义解析器或修改源/目标类型
Source -> DestinationDerived1(目标成员列表)
测试3