AutoMapper:将属性映射推迟到抽象基类的派生映射

时间:2016-11-29 18:20:01

标签: c# .net automapper

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的映射中,而是映射到派生类RegularContractSpecialContract的映射中。

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映射继承来解决这个问题?

0 个答案:

没有答案