如果没有使用目标对象,则有条件地覆盖目标

时间:2012-09-14 00:37:20

标签: automapper

我想设置遵循以下规则的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))

1 个答案:

答案 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));