<< Back to Blog

03 APRIL 2018

AutoMapper C#: UseValue vs ResolveUsing vs MapFrom

There are multiple ways to map a value to an object field using AutoMapper (in ASP.NET C#). Each has its benefits that lend to different situations.

.ResolveUsing(s => {})

// Resolves a value at run time. Use this for DateTime and any dynamic mappings. E.g. DateTime.Now
.UseValue()

// Maps a static value to the object. Use this when the value doesn't change. The value is defined on first-run and stored in mapping. Don’t use for DateTime.Now because the value will be fixed.
.MapFrom(s => s.Name)

// Maps a value from the source object to the destination object.

An example of some confusion I hit when using AutoMapper:

I needed to map DateTime.Now to a field in my object. I wanted DateTime.Now to be evaluated at run-time when the mapping was used. Unfortunately what actually happened was DateTime.Now was evaluated at Startup and the same value was used every time the mapping was called after that - 12:25:01.79... (to the millisecond).

The reason for this was I had used "UseValue" instead of "ResolveUsing":

config.CreateMap<SourceObject, DestObject>()
.ForMember(x => x.DateAdded, opt => opt.UseValue(DateTime.Now)) // Wrong in this case

config.CreateMap<SourceObject, DestObject>()
.ForMember(x => x.DateAdded, opt => opt.ResolveUsing(DateTime.Now)) // Correct