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 to map DateTime.Now to a field in my object. What I wanted to happen: The current value of DateTime.Now to be mapped to my object whenever the mapping was called. What actually happened: The same value of DateTime.Now was being used regardless of when the mapping was called - e.g. the time component was always showing as 12:25:01.7973767 (to the millisecond) even when called minutes apart which alerted me that something was wrong. The reason: I had used the wrong type of mapping, I had used "UseValue" instead of "ResolveUsing":

.ForMember(m => m.DateAdded, o => o.UseValue(DateTime.Now))


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 an actual source object member.
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.