0
votes

I'm fairly new to AutoMapper and want to know how to set a destination member to a value based on a DIFFERENT source property value and if that value is null I just want to apply the default behaviour of Automapper (keep destination value when the source is null)

 CreateMap<ClassA, ClassA>()                   
                    .ForMember(dest => dest.PropertyA, opt =>                             
                            opt.MapFrom(src => src.PropertyB!= null ? null : opt.UseDestinationValue())
                    )

This doesn't work (don't compile) the opt.UseDestinationValue() , what option can I use here? Please help

3

3 Answers

2
votes

Try setting a precondition for mapping destination property.

CreateMap<ClassA, ClassA>().ForMember(dest => dest.PropertyA, opt => opt.PreCondition((src, dest) => src.PropertyB != null));

This will map PropertyA only when PropertyB is not null. I did try a quick sample which gave the desired result.

1
votes

I think you can use the PreCondition option For Mapping Property

        CreateMap<ClassA, ClassA>()
           .ForMember(dest => dest.PropertyA, opt => {
               opt.PreCondition(src => src.PropertyB!= null);
               opt.MapFrom(src => src.PropertyB);
           });

Hope to help you

1
votes

You can do as follows:

var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<ClassA,ClassA>()
    .ForMember(dest => dest.PropertyA, opt => opt.Condition(src => (src.PropertyB!= null)));
});

Or as follows:

var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<ClassA,ClassA>()
    .ForMember(dest => dest.PropertyA, opt => {
        opt.PreCondition(src => (src.PropertyB!=null));
        opt.MapFrom(src => src.PropertyB); // mapping process takes place here
    });
});

But the difference is that, the later runs sooner in the mapping process.

There is an excellent documentation in setting conditions for automapper:

https://docs.automapper.org/en/stable/Conditional-mapping.html