自动映射器 - 将两个不同类型的源集合映射到单个目标集合
本文关键字:集合 映射 同类型 单个 目标集 目标 两个 | 更新日期: 2023-09-27 18:33:06
我在不同类型的源对象上有两个集合。我想将两个集合(两个集合的联合)映射到具有来自两个源类型的所有成员的单个目标集合。如果我这样做:
CreateMap<Company, CompanyResponse>()
.ForMember(x => x.Owners, m => m.MapFrom(x => x.BusinessOwners))
.ForMember(x => x.Owners, m => m.MapFrom(x => x.IndividualOwners));
它仅映射最后一个映射。我尝试了更复杂的映射,但这似乎破坏了自动映射器所做的实体框架投影集成。我正在使用ProjectTo。
这就是我尝试的,它也很好地传达了我想要的结果。
CreateMap<Company, CompanyResponse>()
.ForMember(x => x.Owners, m => m.ResolveUsing(x => x.BusinessOwners.Select(o => new OwnerResponse
{
Type = UpdateRegistrationCommand.CompanyUpdate.OwnerType.Business,
Address = o.Address,
PercentageShareholding = o.Percentage,
BusinessName = o.Name,
BusinessNumber = o.Number
})
.Union(x.IndividualOwners.Select(o => new OwnerResponse
{
Type = UpdateRegistrationCommand.CompanyUpdate.OwnerType.Individual,
Address = o.Address,
PercentageShareholding = o.Percentage,
Title = o.Title,
FirstName = o.FirstName,
MiddleNames = o.MiddleNames,
LastName = o.LastName
}))));
有没有人做过这样的事情?
根据AutoMapper的文档,您可能想尝试ProjectUsing<>()
而不是ResolveUsing<>()
。