自动映射非空属性

时间:2013-09-11 23:49:31

标签: c# automapper

有没有办法使用Automapper将Src映射到Dest,条件如下: - 如果Src的Num为空,则Dest的Num属性应该保持不变 - 如果Src的InnerStr为null,那么Dest的Num属性应该保持不变 - 如果Src的InnerStr无法解析为int,那么Dest的Num应该保持不变 - 如果Src的InnerStr可以解析为int,则Dest的Num值应该设置为该值

对象示例:

public Dest
{
   public int? Num{ get; set; }
}

public Src
{
   public InnerObject Num { get; set; }
}

public InnerObject
{
   public string InnerStr { get; set; }
}

这就是我的尝试:

Mapper.CreateMap<InnerObject, int?>()
   .ConvertUsing(src => 
             { 
                 int x = 0; 
                 //need help here. I'm not sure how to get the source's value at
                 //this point
                 return (int.TryParse(src.Text, out x)) ? new int?(x) : src'svalue; 
             });

Mapper.CreateMap<Src, Dest>();

... 测试:

Dest myDestObj = new Dest()
   {
      Num = new int?(2);
   };

Src nullSrcObj = null;
Src nullStringObj = new Src()
   {
      Num = null;
   };
Src cantBeParsedObj= new Src()
   {
      Num = "I'm not an int!";
   };
Src mySrcObj = new Src()
   {
      Num = "123";
   };

//Should be 2
Console.WriteLine(myDestObj.Num)

Mapper.Map<Src, Dest>(nullSrcObj, myDestObj);

//Should be 2
Console.WriteLine(myDestObj.Num);

Mapper.Map<Src, Dest>(nullStrObj, myDestObj);

//Should be 2
Console.WriteLine(myDestObj.Num);

Mapper.Map<Src, Dest>(cantBeParsedObj, myDestObj);


//Should be 2
Console.WriteLine(myDestObj.Num);

Mapper.Map<Src, Dest>(mySrcObj, myDestObj);


//Should be 123
Console.WriteLine(myDestObj.Num);

1 个答案:

答案 0 :(得分:1)

我认为以下代码是你想要的!

            Mapper.CreateMap<Src, Dest>().ForMember(d => d.Num, expression => expression.ResolveUsing(src =>
            {
                if (src.Num == null)
                {
                    return null;
                }
                else
                {
                    int value;
                    if (int.TryParse(src.Num.InnerStr, out value))
                    {
                        return value;
                    }
                    else
                    {
                        return null;
                    }
                }
            }));