简体   繁体   English

Automapper有时无法映射通过ForMember设置的属性

[英]Automapper occasionally fails to map properties set via ForMember

I've never encountered this odd behavior before from Automapper. 在Automapper之前,我从未遇到过这种奇怪的行为。 To begin with, I'm using Automapper 3.3.0, and Entity Framework 6.1.3. 首先,我使用的是Automapper 3.3.0和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. 除了三(3)个属性外,相关属性的名称在实体和域之间匹配,因此您将在示例代码中看到提供的示例代码中,创建映射时仅存在三(3)个ForMember调用。

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. 但是,有时候,我无法确定具体的复制步骤,除了三(3)个显式映射的属性外,映射成功。

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. 仅供参考,ToList调用旨在防止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. 如果我进行iisreset,一切都很好,它将再次起作用。 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. 当我在Visual Studio 2013中使用调试模式来回走动时,似乎会发生这种情况。就像它只是忘记了如何映射那些属性一样。 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! 谢谢!

Mapper.CreateMap is not thread-safe (nor was ever really intended to be). Mapper.CreateMap不是线程安全的(也从未真正实现过)。 You should only be creating your maps once at startup, typically kicked off for ASP.NET apps in App_Start in Global.asax. 您只应在启动时创建一次地图,通常在Global.asax中的App_Start中为ASP.NET应用程序启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM