在ForMember()中声明变量

时间:2016-07-06 02:11:04

标签: c# automapper

我想声明2个变量,所以我可以转换这段代码:

Mapper.CreateMap<SourceClass, DestinationClass>().ForMember(
    destination => destination.destinationValue, source =>
        source.Condition(resolutionContext =>
            (resolutionContext.InstanceCache.First().Value as DestinationClass).destinationValue2 != null && (resolutionContext.InstanceCache.First().Value as DestinationClass).destinationValue2.Value != ((SourceClass)resolutionContext.Parent.sourceValue).sourceValue2  
            ||
            (resolutionContext.InstanceCache.First().Value as DestinationClass).destinationValue3 != null && (resolutionContext.InstanceCache.First().Value as DestinationClass).destinationValue3.Value != ((SourceClass)resolutionContext.Parent.sourceValue).sourceValue3                                                                          
        ));

进入这个:

Mapper.CreateMap<SourceClass, DestinationClass>().ForMember(
    var sourceObject = ((SourceClass)resolutionContext.Parent.sourceValue);
    var destinationObject = (resolutionContext.InstanceCache.First().Value as DestinationClass);

    destination => destination.destinationValue, source =>
        source.Condition(resolutionContext =>
            destinationObject.destinationValue2 != null && destinationObject.destinationValue2.Value != sourceObject.sourceValue2  
            ||
            destinationObject.destinationValue3 != null && destinationObject.destinationValue3.Value != sourceObject.sourceValue3                                                                          
        ));

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我认为这是一种反模式,因为地图选手应该是愚蠢的,因此你可能想要抵制在其中加入过多逻辑的诱惑。查询缓存是域实施的责任。

也许您应该丰富您映射的域对象,而不是在映射过程中尝试添加缺少的验证和信息。