Search code examples
c#automapper-6

Automapper for member condition


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

Solution

  • You don't need the MapFrom, but you need a PreCondition instead. See here.