[英]AutoMapper - Map two source collections of different types into a single destination collection
[英]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>();
在自定义类型转换器中:
source.Assignments
Map 到List<AssignmentModel>
。.Join()
通过ProductId
加入1和source.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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.