Welcome to EMC Consulting Blogs Sign in | Join | Help

mister mann

every day is just a game of give and take... [ follow me on twitter: @mark_mann ]

AutoMapper Tip: DateTime and UseValue don’t mix

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));
Published 01 August 2011 18:41 by Mark.Mann
Filed under: ,

Comments

No Comments
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems