<< 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#) and it's useful to know the benefits of each in order to choose the right one for a given situation.

First, an example of some confusion I hit when using AutoMapper:

I needed to map DateTime.Now() to a field in my object. I wanted the value of DateTime.Now() to be evaluated at runtime when the mapping was used. Unfortunately what actually happened was the same value of DateTime.Now() was used every time the mapping was called - e.g. 12:25:01.79... (to the millisecond) was always showing no matter when it was called, which alerted me that something was wrong.

The reason for this was I had used the wrong type of mapping. I had used "UseValue" instead of "ResolveUsing":

.ForMember(m => m.DateAdded, o => o.UseValue(DateTime.Now)) // Wrong in this case


ResolveUsing(s => {}) resolves a value at run time. This should be used for DateTime mappings and any more complicated mappings.
MapFrom(s => s.Name) returns a value from the source object.
UseValue() maps a static value to the object. Use when you know the value itself doesn't change because the value is defined on first-run and stored in mapping, it does not change. E.g. don’t use for DateTime.Now because the same value will be used.