簡體   English   中英

AutoMapper - Map collections 不同類型到另一種類型的嵌套集合

[英]AutoMapper - Map collections of different types to collection of another type with nesting

我目前正在努力使用 AutoMapper 版本 10.1.1 配置。 我有以下類型:

class Response
{
    List<Assignment> Assignments { get; }
    List<Product> Products { get; }
}

class Assignment
{
    int AssignmentId { get; set; }
    int ProductId { get; set; } // references Product.ProductId
}

class Product
{
    int ProductId { get; set; }
}

class AssignmentModel
{
    int AssignmentId { get; set; }
    int ProductId { get; set; }
    Product Product { get; set; }
}

對於響應 object 的“Assignments”屬性中的每一項,我想根據產品 ID 獲得一個具有相應產品的新 AssignmentModel。

當前解決方案的工作原理是將 Assignments 映射到新的 AssignmentModels,並將 Products 映射到現有的 AssignmentModels。 缺點是,我必須兩次調用映射器。

cfg.CreateMap<Assignment, AssignmentModel>();
cfg.CreateMap<Product, AssignmentModel>()
    .ForMember(
        d => d.Product, opt => opt.MapFrom(s => s))
    .EqualityComparison((s, d) => s.ProductId == d.ProductId)
    .ForAllOtherMembers(opt => opt.Ignore());

var assignments = mapper.Map<ICollection<AssignmentModel>>(response.Assignments);
mapper.Map(response.Products, assignments); // not using the result because it does not return assignments without products
return assignments;

是否可以在一個電話中做到這一點? 像這樣:

return mapper.Map<ICollection<AssignmentModel>>(response);

建議為您的場景使用自定義類型解析器

映射配置/配置文件

cfg.CreateMap<Assignment, AssignmentModel>();
            
cfg.CreateMap<Response, ICollection<AssignmentModel>>()
    .ConvertUsing<ResponseAssignmentModelCollectionConverter>();

在自定義類型轉換器中:

  1. source.Assignments Map 到List<AssignmentModel>
  2. 使用 LINQ .Join()通過ProductId加入1source.Products的結果。
public class ResponseAssignmentModelCollectionConverter : ITypeConverter<Response, ICollection<AssignmentModel>>
{
    public ICollection<AssignmentModel> Convert(Response source, ICollection<AssignmentModel> destination, ResolutionContext context)
    {
        var _mapper = context.Mapper;

        var result = _mapper.Map<List<AssignmentModel>>(source.Assignments);
        result = result.Join(source.Products, 
        a => a.ProductId, 
        b => b.ProductId, 
        (a, b) =>
        {
            a.Product = b;
            return a;
        })
        .ToList();

        return result;
    }
}
mapper.Map<ICollection<AssignmentModel>>(response);

.NET Fiddle 上的示例演示

暫無
暫無

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

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