inheritance - 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 的意义。
解决方案
推荐阅读
- python - 使用python将文件夹中的所有word文档转换为txt
- r - 在 RShiny 中连接到 BigQuery
- reporting-services - 正确报告组但显示错误的标题
- flutter - Flutter,ListView,如何在ListView顶部添加几个项目并使其不滚动到顶部
- python - pytest 默认跳过标记的测试
- javascript - 无法解决承诺
- python - Jinja2 - 对象在 for 循环中表现不同
- python - 当我从 pandas df 转换为字典时,为什么会丢失记录?
- php - 登录后如何显示我的管理员全名 - Codeigniter
- java - 如何使用长整数设置 SeekBar 进度?(或替代品)