Reputation: 107
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.
Upvotes: 2
Views: 2355
Reputation: 1202
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)));
Upvotes: 0
Reputation: 21
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))
Upvotes: 2