AutoMapper: UseValue vs ResolveUsing vs MapFrom

I just hit a confusing mapping bug whilst using AutoMapper to map DateTime.Now to a field in my database. Every item that was being added to the database had the same value in the "DateAdded" - to the millisecond. This was because I was using the following mapping expression:

Mapper.CreateMap<SourceObject, DestObject>()
.ForMember(m => m.DateAdded, o => o.UseValue(DateTime.Now));

UseValue() retrieves a value on first-run and stores it in the mapping (hence the static DateTime value that's being stored in the database), whereas ResolveUsing() resolves at run-time - which is obviously why it's called ResolveUsing(). A minor oversight, but confusing nonetheless.

  • Use ResolveUsing(s => {}) when you want to resolve a destination field from a derived value. This should be used for any DateTime mappings, and any more complicated mapping functions.
  • Use MapFrom(s => s.MemberName) when you return an actual source object member.
  • Use UseValue() if you want to map a static value in the mapping, and you know the value itself won't change.

Popular posts from this blog

Getting Unity 3D working with Git on Windows

MVC3: Redirect Action to HTML Bookmark

Deleting All PlayerPrefs for your Unity3D Project on Windows