Automapper occasionally fails to map properties set via ForMember

automapper automapper-3 c# entity-framework-6


I've never encountered this odd behavior before from Automapper. To begin with, I'm using Automapper 3.3.0, and Entity Framework 6.1.3. I have a method that retrieves entity data via entity framework. Prior to returning the data, it is mapping it to a domain model. With the exception of three (3) of the properties, the names of pertinent properties match between entity and domain, thus you will see in the sample code that I provide that there are simply three (3) ForMember calls when creating the map.

This works fine most of the time, as I would expect it should. However, occasionally, and I can't for the life of me nail down the exact steps to repro, the mapping succeeds with the exception of the three (3) explicitly mapped properties.

Here's the code that I believe is pertinent:

var dailyPriceHistories = 
  MapToDomain(_clearDbEntities.get_DailyPriceHistory(startDate.Date, endDate.Date).ToList());

FYI, the ToList call is intended to prevent lazy loading problems from EF.

And, the mapper:

private static IList<DailyPriceHistory> MapToDomain(List<get_DailyPriceHistory_Result> someDataEntities)
    Mapper.CreateMap<get_DailyPriceHistory_Result, DailyPriceHistory>()
        .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.DailyPriceHistory_ID))
        .ForMember(dest => dest.ProductId, opt => opt.MapFrom(src => src.AllProducts_ID))
        .ForMember(dest => dest.DateInfoId, opt => opt.MapFrom(src => src.DateInfo_ID));

    return Mapper.Map<List<get_DailyPriceHistory_Result>, List<DailyPriceHistory>>(dailyPriceHistoryEntities);

If I do an iisreset, everything is fine, it works again. It seems to occur when I've gone back and forth a bit with debug mode in Visual Studio 2013. It's like it just forgets how to map those properties. The entity data being passed in does always contain the values, by the way, it simply fails to map the three of them to the domain.

Any help would be greatly appreciated. Thanks!

8/9/2015 6:49:02 PM

Accepted Answer

Mapper.CreateMap is not thread-safe (nor was ever really intended to be). You should only be creating your maps once at startup, typically kicked off for ASP.NET apps in App_Start in Global.asax.

8/10/2015 12:22:08 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow