问题描述
有两种类型:
1)DTO类型:
[DataContract]
public sealed class OrderDetailDto
{
[DataMember]
public Guid MergeId { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string PostionName { get; set; }
[DataMember]
public decimal Quantity { get; set; }
[DataMember]
public byte[] Version { get; set; }
}
2),对应域类型:
2) corresponding domain type:
public sealed class OrderDetail
{
public Guid MergeId { get; set; }
public int Id { get; set; }
public string PostionName { get; set; }
public decimal Quantity { get; set; }
public byte[] Version { get; set; }
}
和两个集合:收藏<的OrderDetail>
和收集和LT; OrderDetailDto>
。
收集和LT; OrderDetailDto>
的数据的变化,这是什么地方的。现在我想将这些修改收集和LT;&的OrderDetail GT;
,使用Automapper。
Collection<OrderDetailDto>
has data changes, that was made somewhere. Now I want to apply these changes to Collection<OrderDetail>
, using Automapper.
为了简单起见,我们认为,这项数的在这些集合是相等的,但是项目的为了的可能不同。
For simplicity, let's think, that items count in these collections are equal, but the order of items may differ.
要正确映射藏品,我想用 MergeId
属性。我需要的是这样的:
To map collection items correctly, I want to use MergeId
property. I need something like this:
Mapper.CreateMap<Collection<OrderDetailDto>, Collection<OrderDetail>>()
.MappingExpression((dto, do) => dto.MergeId == do.MergeId);
这是可以做到与Automapper?
Is this possible to do with Automapper?
推荐答案
我还没有发现比使用自定义转换器像下面更好的解决方案。
I have not found better solution than using custom converter like below.
public class Converter : ITypeConverter<Collection<OrderDetailDto>, Collection<OrderDetail>>
{
public Collection<OrderDetail> Convert(ResolutionContext context)
{
var destCollection = (Collection<OrderDetail>) context.DestinationValue;
var sourceCollection = (Collection<OrderDetailDto>)context.SourceValue;
foreach (var source in sourceCollection)
{
var dest = destCollection.SingleOrDefault(d => d.MergeId == source.MergeId);
Mapper.Map(source, dest);
}
return destCollection;
}
}
这篇关于合并两个集合与Automapper由条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!