2013-11-14 74 views
0

我有一件奇怪的事情发生在automapper上。AutoMapper IEnumerable映射错误

难道有人有线索,为什么这个代码是为InstitutionsImplantations场返回值:

var result1 = new List<DataModel.Implantations>(); 
foreach (var c in collection) 
{ 
    DataModel.Implantations i = Mapper.Map<DataModel.Implantations>(c); 
    result1.Add(i); 
} 
var item1 = result1.Where(x => x.Nom == "Valdor").FirstOrDefault(); 
Console.WriteLine(item1.InstitutionsImplantations); 

虽然这一个(在相同的集合),用于InstitutionsImplantations返回null:

var result2 = Mapper.Map<IEnumerable<DataModel.Implantations>>(collection); 
var item2 = result2.Where(x => x.Nom == "Valdor").FirstOrDefault(); 
Console.WriteLine(item2.InstitutionsImplantations); 

事实: autommaper在IEnumerable上完成的映射对于列表中的+/- 300个项目是正确的,然后是某个项目集合具有“严重”映射的InstitutionsImplantations属性。

InstitutionsImplantations属性是来自EF结果的对象“代理”。

你知道为什么会发生这种情况吗?

Tx you!

+0

从来没有见过类似的东西,但使用AutoMapper的“正常”方法是'collection.Select(c => Mapper.Map (c))''所以你不需要臃肿的'IEnumerable'映射。这种形式基本上与您的第一个片段相同。不回答当然的问题。知道这是否是一个bug会很有趣。 –

回答

1

发现问题,使用automapper源代码来查看幕后发生了什么。

当automapper处理IEnumerable集合时,它使用缓存机制来避免必须重新映射集合中存在的已映射对象。

你会说,它的公平,没有理由有相同的对象映射到不同的结果。

但在我的情况下,我忘了补充说我还在映射声明中使用了一个AfterMap委托。

在这种AfterMap我这样做(为了避免循环引用的问题):

mappedItem.InstitutionsImplantations.Institution.InstitutionsImplantations = null; 

的这此问题是,我虽然它只是影响的映射(AfterMap代表)的结果,没有别的,但我错了,它也正在影响正在实施的“Cache”! 这不是我想要的,因为在这种情况下,它也会影响集合中的所有映射计算,对于以下映射的InstitutionsImplantations对象使用“Null”而不是全新的映射。

我的第一个解决方案很干净,因为缓存机制在2个“不同”映射之间不起作用。 而我没有找到一个简单的方法来禁用automapper中的这个集合缓存机制!