自动映射器:继承的映射不包含扁平化的属性

时间:2019-07-09 17:51:36

标签: inheritance automapper

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

虽然我可以使用.IncludeMembers()进行展平从实体映射到基本DTO,但是当我尝试使用.IncludeBase<Customer, CustomerDtoBase>为派生DTO添加映射时,它会抛出错误,因为它无法检测到未明确映射的属性。

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

// 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的目的就不成立了。

0 个答案:

没有答案