AutoMapper是否可以将一些属性映射到派生地图?例如,考虑以下类:
public abstract class Contract
{
public int ContractNumber { get; set; }
}
public class RegularContract : Contract { }
public class SpecialContract : Contract { }
public class ContractModel
{
public int Nr { get; set; }
public bool IsSpecial { get; set; }
}
我想创建如下的映射。注意IsSpecial
属性未映射到Contract
的映射中,而是映射到派生类RegularContract
和SpecialContract
的映射中。
public class ContractMappingProfile : Profile
{
public ContractMappingProfile()
{
CreateMap<Contract, ContractModel>()
// .ForMember(t => t.IsSpecial, c => c.Ignore()) // required for valid mapping
.ForMember(t => t.Nr, c => c.MapFrom(s => s.ContractNumber));
CreateMap<RegularContract, ContractModel>()
.IncludeBase<Contract, ContractModel>()
.ForMember(t => t.IsSpecial, c => c.UseValue(false));
CreateMap<SpecialContract, ContractModel>()
.IncludeBase<Contract, ContractModel>()
.ForMember(t => t.IsSpecial, c => c.UseValue(true));
}
}
但是,这样的配置在AutoMapper中无效,因为IsSpecial
未映射Contract
。为了使其有效,我需要将注释行添加到映射中。
但是,在这种情况下,如果属性未在某些派生类中映射,则AutoMapper不会抛出验证错误,例如,当我将SpecialContract
的映射更改为:
CreateMap<SpecialContract, ContractModel>()
.IncludeBase<Contract, ContractModel>(); // no IsSpecial mapping
如何使用AutoMapper映射继承来解决这个问题?