Teeknow
Teeknow

Reputation: 1015

Automapper Mapping Non-null properties

Is there a way to use Automapper to map Src to Dest with the following conditions: -If Src's Num is null then Dest's Num property should stay the same -If Src's InnerStr is null then Dest's Num property should stay the same -If Src's InnerStr cannot be parsed as an int then Dest's Num should stay the same -If Src's InnerStr can be parsed as an int then Dest's Num's value should be set to that value

Object example:

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

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

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

Here's what I was trying:

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>();

... The test:

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

Upvotes: 0

Views: 653

Answers (1)

czclk
czclk

Reputation: 157

I think the following codes are what you wanted!

            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;
                    }
                }
            }));

Upvotes: 1

Related Questions