2011-11-04 88 views
5

问题 看起来像条件​​被忽略。这是我的情景:自动映射器的状态被忽略

源类

public class Source 
{ 
    public IEnumerable<Enum1> Prop1{ get; set; } 

    public IEnumerable<Enum2> Prop2{ get; set; } 

    public IEnumerable<Enum3> Prop3{ get; set; } 
} 

从一个字节的枚举子类,然后用[标志]装饰。目标类只包含Enum1,Enum2和Enum3等属性,包含“总”位值。所以在本质上,如果Enumeration包含Enum1.value!,Enum1.Value2和Enum1.Value3,则目标将包含Enum1.Value1 | Enum1.Value2 |当内属性非空值和映射成功和正确地设定目的地Enum1.Value3

目的类

public Enum1 Prop1 { get; set; } 

    public Enum2 Prop2 { get; set; } 

    public Enum3 Prop3 { get; set; } 

AutoMapper映射

Mapper.CreateMap<Source, Destination>() 
      .ForMember(m => m.Prop1, o => 
       { 
        o.Condition(c => !c.IsSourceValueNull); 
        o.MapFrom(f => f.Prop1.Aggregate((current, next) => current | next)); 
       }) 
      .ForMember(m => m.Prop2, o => 
      { 
       o.Condition(c => !c.IsSourceValueNull); 
       o.MapFrom(f => f.Prop2.Aggregate((current, next) => current | next)); 
      }) 
      .ForMember(m => m.Prop3, o => 
      { 
       o.Condition(c => !c.IsSourceValueNull); 
       o.MapFrom(f => f.Prop3.Aggregate((current, next) => current | next)); 
      }); 

映射工作正常。但是,当成员源值为空(当Prop1为null时,则跳过映射)时,我想跳过映射。

我可以从调试中看到Source.Prop1为空。条件完全被忽略,并得到异常说值为空。

Trying to map Source to Destination. Destination property: Prop1. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. --> Value cannot be null. Parameter name: source 

我不确定是否IsSourceValueNull检查Prop1或实际的Source类不是null。只有成员Prop1为空。

任何帮助isappreciated。

回答

6

我认为你需要做的ConditionMapFrom两个步骤:如果条件计算结果为假

.ForMember(c => c.Prop1, o => o.Condition(c => !c.IsSourceValueNull)); 
.ForMember(c => c.Prop1, o => o.MapFrom(f => f.Prop1.Aggregate(...)); 

的MapFrom将永远不会被使用。

编辑

嗯...这似乎并没有工作。我以为我曾经在某个地方使用过。你可以求助于MapFrom:

.MapFrom(f => f.Prop1 == null ? null : f.Prop1.Aggregate(...)); 
+0

谢谢帕特里克。通过分离出来,我可以得到完全相同的例外。 – TimJohnson

+0

我以为我以前做过。一种可能的情况是,c.IsSourceValueNull可能表示整个要映射的源对象是否为空。我想知道它应该是“c => c.Prop1!= null”? – PatrickSteele

+0

使用“条件”找不到代码示例。抱歉。我想你总是可以这样做:o.MapFrom(f => f.Prop1 == null?null:f.Prop1.Aggregate(...)) – PatrickSteele

2

IMO,这实际上是AutoMapper的EnumMapper中的一个错误。条件声明,正如你在上面所说的那样,应该可以正常工作。例如,当映射从一个具体类型到另一个TypeMapMapper将正确调用条件:

object mappedObject = !context.TypeMap.ShouldAssignValue(context) ? null : mapperToUse.Map(context, mapper); 

最终调用defined condition

public bool ShouldAssignValue(ResolutionContext context) 
    { 
     return _condition == null || _condition(context); 
    } 

EnumMapper不调用类型映射的ShouldAssignValue方法以确定它是否确实应该映射该领域。同样,我没有看到AfterMap的任何提及,所以这里定义的任何东西都不可能发挥作用。

+0

作为问题#143提交一个测试用例: https://github.com/AutoMapper/AutoMapper/issues/143 –

+0

谢谢。这就说得通了。 – TimJohnson