首页 > 解决方案 > Automapper:继承的映射不包括扁平化的属性

问题描述

我正在使用 AutoMapper 从包含各种值对象的实体映射到平面 DTO。

虽然我可以使用 展开从实体映射到基本 DTO .IncludeMembers(),但当我尝试使用 为派生 DTO 添加映射时.IncludeBase<Customer, CustomerDtoBase>,它会引发错误,因为它不会检测未显式映射的属性。

这是一些说明问题的示例代码。(取消注释底部映射以查看错误):

// Entity
public class Customer
{
    public int Id { get; protected set; }
    public string Name { get; protected set;}
    public Address Address { get; protected set; }
}

// Value object
public class Address
{
    public string Line1 { get; private set; }
    public string Postcode { get; private set; }
}

// Base Dto
public class CustomerDtoBase
{
    public int Id { get; protected set; }
    public string Name { get; protected set;}
    public string AddressLine1 { get; protected set; }
    public string Postcode { get; protected set;}
}

// Derived DTO
public class CreateCustomerDto : CustomerDtoBase
{
    public string CreatedBy { get; protected set; }
}

// Derived DTO
public class UpdateCustomerDto : CustomerDtoBase
{
    public string UpdatedBy { get; protected set; }
}

public static class AutoMapperConfiguration
{
    public static IMapper Configure()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<CustomProfile>();
        });

        config.AssertConfigurationIsValid();

        return config.CreateMapper();
    }
}

internal class CustomProfile : Profile
{
    public CustomProfile()
    {       
        CreateMap<Customer, CustomerDtoBase>()
            .IncludeMembers(x => x.Address)
            .ForMember(m => m.Id, o => o.Ignore());

        // This uses default convention to map Postcode
        CreateMap<Address, CustomerDtoBase>(MemberList.None)
            .ForMember(m => m.AddressLine1, o => o.MapFrom(x => x.Line1));

/*  
        // This throws an error that Postcode has not been mapped
        CreateMap<Customer, CreateCustomerDto>()
            .IncludeBase<Customer, CustomerDtoBase>()
            .ForMember(m => m.CreatedBy, o => o.Ignore());

        // This throws an error that Postcode has not been mapped
        CreateMap<Customer, UpdateCustomerDto>()
            .IncludeBase<Customer, CustomerDtoBase>()
            .ForMember(m => m.UpdatedBy, o => o.Ignore());
*/          
    }
}

void Main()
{
    var mapper = AutoMapperConfiguration.Configure();   
}

此映射是否存在不正确或缺失的内容?或者 AutoMapper 中是否存在错误/不支持此功能?

我可以通过显式添加嵌套对象映射的所有映射来解决此问题,例如.ForMember(m => m.Postcode, o => o.MapFrom(x => x.Postcode))等。但是如果您必须显式映射每个属性,它就会破坏使用 AutoMapper 的意义。

标签: inheritanceautomapper

解决方案


推荐阅读