2

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);
Wojciech Szabowicz
  • 3,646
  • 5
  • 43
  • 87

2 Answers2

2

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;
    }
}
Alex Sanséau
  • 8,250
  • 5
  • 20
  • 25
  • And what if I want a value from x instead of string empty. – Wojciech Szabowicz Sep 28 '17 at 11:24
  • @WojciechSzabowicz, I edited my response to add 2 more examples. Hope it helps. – Alex Sanséau Sep 28 '17 at 11:47
  • 1
    @AlexSanséau That code will never set destination to `string.Empty` because if `ClassA.Branch` is null, that field will not be mapped. That's the default AutoMapper behavior. `Branch` will have a value of `string.Empty` only if the default constructor for `Class` initializes it that way. – Suncat2000 Jul 09 '19 at 20:19
0

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

Lucian Bargaoanu
  • 3,336
  • 3
  • 14
  • 19