Automapper for member condition

Wojciech Szabowicz picture Wojciech Szabowicz · Sep 28, 2017 · Viewed 8k times · Source

I am using auto mapper 6.1 and I want to map some values from one object to another, but there is a condition that those values can not be null and not all object properties are supposed to be mapped if so I could easily use ForAllMembers conditions. What I am trying to do is:

   config.CreateMap<ClassA, ClassB>()
     .ForMember(x => x.Branch, opt => opt.Condition(src => src.Branch != null), 
        cd => cd.MapFrom(map => map.Branch ?? x.Branch))

Also tried

 config.CreateMap<ClassA, ClassB>().ForMember(x => x.Branch, cd => {
   cd.Condition(map => map.Branch != null);
   cd.MapFrom(map => map.Branch);
 })

In another words for every property I define in auto mapper configuration I want to check if its null, and if it is null leave value from x.

Call for such auto mapper configuration would look like:

 ClassA platform = Mapper.Map<ClassA>(classB);

Answer

Alex Sans&#233;au picture Alex Sanséau · Sep 28, 2017

If I've understood correctly, it may be simpler than you think. The opt.Condition is not necessary because the condition is already being taken care of in MapFrom.

I think the following should achieve what you want: it will map Branch if it's not null. If Branch (from the source) is null, then it will set the destination to string.Empty.

config.CreateMap<ClassA, Class>()
    .ForMember(x => x.Branch, cd => cd.MapFrom(map => map.Branch ?? string.Empty));

And if you need to use another property from x instead of string.Empty, then you can write:

config.CreateMap<ClassA, Class>()
    .ForMember(x => x.Branch, cd => cd.MapFrom(map => map.Branch ?? x.AnotherProperty));

If you want to implement complex logic but keep the mapping neat, you can extract your logic into a separate method. For instance:

config.CreateMap<ClassA, Class>()
        .ForMember(x => x.Branch, cd => cd.MapFrom(map => MyCustomMapping(map)));

private static string MyCustomMapping(ClassA source)
{
    if (source.Branch == null)
    {
        // Do something
    }
    else
    {
        return source.Branch;
    }
}