3
我想设置遵循以下规则的自动映射器映射。如果没有使用目标对象,有条件地覆盖目标
- 如果未使用“就地”目的地语法,如果对象被传递在特定成员映射到值
- ,然后使用目的地值
我已经试过这是我能想到的每一种方式。类似这样的:
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))
不幸的是,这是行不通的。它每次都会覆盖传入的值。 –
事实证明,你必须引用parent.DestinationValue,但我已经upvoted反正。 –
有趣......感谢upvote! – PatrickSteele