automapperautomapper-8

Automapper 8 - An expression tree lambda may not contain a null propagating operator


Automapper version 8.0.0 removed ResolveUsing extension method from IMappingExpression and consolidated it with MapFrom extension method. However, after replacing ResolveUsing with MapFrom method, certain configurations throw exception.

Original ResolveUsing:

CreateMap<SourceType, DestinationType>()
    .ForMember(dest => dest.Customer,
        opt => opt.ResolveUsing(src => src?.Customer ?? new Customer())
    );

Replaced with MapFrom:

CreateMap<SourceType, DestinationType>()
    .ForMember(dest => dest.Customer,
        opt => opt.MapFrom(src => src?.Customer ?? new Customer())
    );

This produces compilation error:

Error CS8072

Automapper

An expression tree lambda may not contain a null propagating operator.


Solution

  • New Func-based overloads in Automapper 8.0.0 accept more parameters compared to old/removed ResolveUsing overloads.

    Instead of using lambda expression with single input parameter opt.MapFrom(src => ...) when replacing ResolveUsing, overload with 2 parameters should be used opt.MapFrom((src, dest) => ...).

    MapFrom expression becomes:

    opt => opt.MapFrom((src, dest) => src?.Customer ?? new Customer())
    

    Full example:

    CreateMap<SourceType, DestinationType>()
        .ForMember(dest => dest.Customer,
            opt => opt.MapFrom((src, dest) => src?.Customer ?? new Customer())
        );