Automapper copy based on destination value

1.7k Views Asked by At

I am trying to copy source value only if the destination value is null. I am using the following map

 Mapper.CreateMap<BM.AudioSetting, BM.AudioSetting>()
        .ForMember(dest => dest.MSOffsetInherited, opt =>
                                                       {
                                                           opt.Condition(src => src.DestinationValue == null);
                                                           opt.MapFrom(src => src.MSOffset);
                                                       });

In my condition I am checking to make sure the destination value is null before mapping. The problem is the copying is happening all the time regardless of the destination value.

Am I doing this wrong?

Thanks Isam

2

There are 2 best solutions below

0
On

Your code should work fine. Probably you're expecting src.DestinationValue to be the destination object's property. If so, custom type converter should help you to achieve desired behavior.

This post should help you with creating custom type converter.

0
On

I notice your source and destination types are the same. Are you essentially trying to clone the object when the destination value is null? If so, then AutoMapper may not be the appropriate solution as per the comments on this question: Copy object to object (with Automapper ?)