<< Back to Blog

03 APRIL 2018

AutoMapper C#: UseValue vs ResolveUsing vs MapFrom

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<Source, Dest>()
.ForMember(x => x.DateAdded, opt => opt.UseValue(DateTime.Now)) // Wrong in this case


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

.ResolveUsing(s => {})
// Resolves a value at run time. This should be used for DateTime mappings and any dynamic mappings.
// Maps a static value to the object. Use 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 same value will be used.
.MapFrom(s => s.Name)
// Returns a value from the source object.