AutoMapper - 将两个不同类型的源集合映射到单个目标集合中

时间:2016-02-04 06:51:38

标签: c# entity-framework automapper

我在不同类型的源对象上有两个集合。我想将两个集合(两者的并集)映射到一个类型的目标集合,该集合具有来自两个源类型的所有成员。如果我这样做:

CreateMap<Company, CompanyResponse>()
                .ForMember(x => x.Owners, m => m.MapFrom(x => x.BusinessOwners))
                .ForMember(x => x.Owners, m => m.MapFrom(x => x.IndividualOwners));

它只映射最后一个映射。我尝试了更精细的映射,但这似乎打破了automapper所做的实体框架投影集成。我正在使用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
        }))));

有人做过这样的事吗?

1 个答案:

答案 0 :(得分:1)

根据AutoMapper's documentation,您可能想尝试ProjectUsing<>()而不是ResolveUsing<>()