2

I have a mapper in place and I need to perform a conditional mapping, Condition is, map the value from source to destination only if the destination property value is null. How would I do that?

.ForMember(o => o.EmployeeId, opt => opt.MapFrom(u => u.EmployeeId))

I want to assign value to EmployeeId only if it does't have a value already.

5
  • docs.automapper.org/en/v9.0.0/Conditional-mapping.html Commented Nov 24, 2019 at 16:15
  • Thanks Lucian for response, I did go through this documentation before posting here, in documentation and all the other places I only found a way to put condition on source property not on destination property. Commented Nov 24, 2019 at 16:22
  • There are many Condition/PreCondition overloads. You just have to find the right one. Commented Nov 24, 2019 at 16:43
  • Yes and all those methods work only on source object property. I did find a way of writing it on destination object property. Commented Nov 24, 2019 at 17:19
  • You get the destination object. Commented Nov 24, 2019 at 19:43

2 Answers 2

2

The method of IMemberConfigurationExpression .MapFrom() has the overload that takes an IDestination void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction); In your mapping function you can check the destination object.

Example:

.ForMember(dest => dest.EmployeeId, opt => opt.MapFrom((src, dest) => dest ?? src.EmployeeId))
Sign up to request clarification or add additional context in comments.

Comments

0

Late answer but may help someone. This is what ended up working for me in ASP Net 6

//Only add email address if email is null or empty on the destination user object
CreateMap<UserProfile, User>()
            .ForMember(dest => dest.Email, opt => opt.PreCondition((src, dest, ctx) => string.IsNullOrEmpty(dest.Email)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.