Automapper Magic - MapFrom v ResolveUsing saving you from Nulls

Automapper Magic - MapFrom v ResolveUsing saving you from Nulls

A quick post regarding AutoMapper. I normally use it from API models with a WebAPI project as it helps heavenly in the code monkey data mapping work one must do. I do love it.

However, I ran into an interesting problem which I've ran into time and time again but always forget to do, this time I'll create a post to save you pain of having to discover it yourself.

TL;DR

In AutoMapper when attempting to map a property of your class which is inherited from a base class, if you use the IMemberConfigurationExpression<>.ResolveUsing() function to map, it will throw a NullReferenceException if the object is Null. However, if you use IMemberConfigurationExpression<>.MapUsing() it will provide pretty much the same functionality as ResolveUsing, however, it also does a Null check so if the objects you are mapping from are Null, if so it will auto-assign a Null to the destination object.

Simple Example

Say we have an object we want to map which has two layers of base classes like so:

Mapper.CreateMap<CalculatorApiModel, Calculator>()
    .ForMember(dest => dest.Operation.Chosen, src => src.ResolveUsing(src => ChosenOperation));

If CalculatorApiModel.ChosenOperation was Null when attempting to map to Calculator, you would get a NUllReferenceException and have to handle the Null case yourself.

Mapper.CreateMap<CalculatorApiModel, Calculator>()
    .ForMember(dest => dest.Operation.Chosen, src => src.MapFrom(src => ChosenOperation));

In this case, if CalculatorApiModel.ChosenOperation was Null when attempting to map to Calculator, Calculator.Operation.Chosen would be Null, for free.

MapFrom uses an Expression to do the resolution but also preforms Null checks all the way down to the base objects, a Null will be assigned automatically to the property if it deserves it.

While ResolveUsing uses a Func, it does not do any Null checks and thus may throw an exception in your models. Thus if your business/domain logic can allow this property to be Null and to proceed with code execution, you'll have to do a bit more work to map the Null value there.

MapFrom just saves you here.