I’ve been using AutoMapper on a number of projects for a number of years now and it’s always been a love/hate relationship. AutoMapper is a great  little .NET class library that takes the pain out of mapping one class to another but sometimes it makes me nervous when I just trust the magic and wonder what it’s really doing because although it hides the chore of reams of mapping code, is it also hiding mismappings? Just to prove this point, I discovered an innocent misuse of the AutoMapper configuration in my current project…

For some bizarre reason, the timestamp property on one of our C# classes seemed to be stuck in the past – across all instances it was the exactly the same time, rather than updating to the current time. The only place where the time was set, was in the following AutoMapper profile declaration:

Mapper.CreateMap<LoginPostModel, LoginAuditDetail>()
    .ForMember(dest => dest.OccurredAt, opt => opt.UseValue(DateTime.UtcNow));

Reason is because, UseValue is a static, so it’s set once when the MapProfile is instantiated and all subsequent .Map() invokes will use the same static value. Hence the sticky time value.

Mapper.CreateMap<LoginPostModel, LoginAuditDetail>()
    .ForMember(dest => dest.OccurredAt, opt => opt.MapFrom(src => DateTime.UtcNow));


So when would you use UseValue ? Using a static value would be more applicable when setting up fixed Enums or custom values that are dependent on the mapping. For example:

Mapper.CreateMap<Account, CurrentAccount>()
    .ForMember(dest > dest.InterestCalculated, opt => opt.MapFrom(src => InterestCalculatedEnum.Daily));

Mapper.CreateMap<Account, SavingsAccount>()
    .ForMember(dest => dest.InterestCalculated, opt => opt.MapFrom(src => InterestCalculatedEnum.Monthly));

Mapper.CreateMap<Account, BondAccount>()
    .ForMember(dest => dest.InterestCalculated, opt => opt.MapFrom(src => InterestCalculatedEnum.Annual));


This is a cross post from my EMC blog, mainly for backup duplicity and to aggregate some of my past postings. My EMC blog used to be under the Conchango brand but was acquired by EMC so I’ve also retrospectively refreshed some of the old links and maybe a tweak a bit of content too.
permalink to the original post here