簡體   English   中英

AutoMapper-將兩個不同類型的源集合映射到一個目標集合中

[英]AutoMapper - Map two source collections of different types into a single destination collection

我在不同類型的源對象上有兩個集合。 我想將兩個集合(兩個的並集)映射到具有來自兩個源類型的所有成員的類型的單個目標集合。 如果我這樣做:

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<>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM