Krishnandu Sarkar
Krishnandu Sarkar

Reputation: 484

AutoMapper ignore NULL values

There seems to be lots of confusion regarding how to achieve this in latest update AutoMapper. I'm using AutoMapper 5.2.0 and the old solutions found on Github Issues and SO are not working.

My requirement is to ignore the mapping if source value is null or empty (for strings) or 0 (for int)

Upvotes: 0

Views: 1066

Answers (1)

Brecht
Brecht

Reputation: 41

Try using this extension for checking if null:

public static void MapFromIfNotNull<TSource, TDestination, TProperty>(
        this IMemberConfigurationExpression<TSource, TDestination, TProperty> map, 
        Expression<Func<TSource, object>> selector)
        {
            var function = selector.Compile();
            map.Condition(source => function(source) != null);
            map.MapFrom(selector);
        }

Then use

CreateMap<EmployeeDTO, Employee>()
   .ForMember(dest => dest.MOBILE, opts => opts.MapFromIfNotNull(src => src.MobilePhone))

Upvotes: 2

Related Questions