简体   繁体   中英

how to map only if destination object doesn't have a value in Automapper

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.

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.EmployeeId ?? src.EmployeeId))

It's should be help you.

CreateMap<YOURMODEL,YOURMODEL2>()
    .ForMember(dest => dest.EmployeeId, opt => {
        opt.PreCondition(src => src.EmployeeId != null);
        opt.MapFrom(src => src.EmployeeId);

Other way

CreateMap<SourceClass, TargetClass>()
    .ForMember(d => d.EmployeeId, o => o.MapFrom(s => s.EmployeeId))
    .ForAllMembers(o => o.Condition((src, dest, value) => value != null));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM