12

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.

Community
  • 1
  • 1
Nenad
  • 24,809
  • 11
  • 75
  • 93
  • Why is this configuration even necessary? This looks like the default behavior of mapping. – Jimmy Bogard Jan 07 '19 at 14:55
  • 1
    It is simplified example, to emphasize `Error CS8027` when using `null propagation operator`. Real situation mapping configuration is more complex. – Nenad Jan 07 '19 at 15:40

1 Answers1

29

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())
    );
Nenad
  • 24,809
  • 11
  • 75
  • 93
  • 2
    There is a built in feature for this, NullSubstitute. – Lucian Bargaoanu Jan 04 '19 at 09:58
  • Why the nonoverload methos won't compile? And how come the second overload resolves this? – Royi Namir Jun 25 '21 at 07:19
  • @RoyiNamir It's mentioned in the answer already. Old method uses `Func` input parameter. New method uses lambda expression as the input parameter. Although they are mostly similar, there are different constraints in the compiler, like Error CS8072. The overload uses `Func`, so it's fully compatible with the old method. – Nenad Jun 28 '21 at 09:04