Using automapper change destination value only if it is equal to 0

Viewed 3969

I am trying to make Automapper change dsetination value only if it equals to a specific value. So I don't care what the source value is I just want to look at the destination value before mapping and if it equals to 0 then I want to do the mapping if it is >0 then I don't want to map this.

So far I can only come up with a method that does this but the other way around. It looks at the source and if the source value satisfies the condition it will map. Looks like this:

 CreateMap<SurveyResource, Survey>()

            .ForMember(dest => dest.ClientId, opt =>
            {
                   opt.Condition(src => src.ClientId == 0);
                   opt.MapFrom(src => src.ClientId);
            });

This will look as SurveyResource ClientId value and if it equals to 0 then it will paste 0 into the destination (ie. it will paste current source value of client id). Does anybody know how to do this the other way around? Do I have to use custom value resolvers?

1 Answers

Man, you are so close!

CreateMap<SurveyResource, Survey>()
    .ForMember(dest => dest.ClientId, opt =>
    {
         opt.Condition((src, dest) => dest.ClientId == 0);// suppose dest is not null.
         opt.MapFrom(src => src.ClientId);
     });
Related