我想设置遵循以下规则的Automapper映射。
我已经尝试过各种我能想到的方式。像这样:
Mapper.CreateMap<A, B>()
.ForMember(dest => dest.RowCreatedDateTime, opt => {
opt.Condition(dest => dest.DestinationValue == null);
opt.UseValue(DateTime.Now);
});
这始终映射值。基本上我想要的是这个:
c = Mapper.Map<A, B>(a, b); // does not overwrite the existing b.RowCreatedDateTime
c = Mapper.Map<B>(a); // uses DateTime.Now for c.RowCreatedDateTime
注意:A不包含RowCreatedDateTime。
我有什么选择?这非常令人沮丧,因为似乎没有关于Condition方法的文档,并且所有google结果似乎都集中在源值为null的位置,而不是目标。
编辑:
感谢帕特里克,他让我走上正轨......
我找到了解决方案。如果有人有更好的方法,请告诉我。注意我必须引用dest.Parent.DestinationValue
而不是dest.DestinationValue
。出于某种原因,dest.DestinationValue
始终为空。
.ForMember(d => d.RowCreatedDateTime, o => o.Condition(d => dest.Parent.DestinationValue != null))
.ForMember(d => d.RowCreatedDateTime, o => o.UseValue(DateTime.Now))
答案 0 :(得分:4)
我认为您需要设置两个映射:一个使用Condition
(确定IF应该执行映射),另一个定义Condition
返回true时要执行的操作。像这样:
.ForMember(d => d.RowCreatedDateTime, o => o.Condition(d => d.DestinationValue == null);
.ForMember(d => d.RowCreatedDateTime, o => o.UseValue(DateTime.Now));