[英]AutoMapper IEnumerable mapping bug
自动映射器发生了一件奇怪的事情。
是否有人知道为什么此代码返回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结果中的对象“代理”。
您知道为什么会这样吗?
谢谢你!
发现了问题,使用自动映射器源代码查看了幕后情况。
当自动映射器处理IEnumerable集合时,它使用缓存机制来避免必须重新映射该集合中存在的已映射对象。
您会说,这是公平的,没有理由将相同的对象映射到不同的结果。
但是在我的场景中,我忘了补充一点,我还在映射声明中使用了AfterMap委托。
在此AfterMap中,我正在这样做(以避免循环引用问题):
mappedItem.InstitutionsImplantations.Institution.InstitutionsImplantations = null;
这个问题是,尽管我只影响映射的结果(AfterMap委托),而没有别的什么,但是我错了,它还影响到放置的“缓存”! 这不是我想要的,因为在这种情况下,它还会影响集合中所有后续映射计算,对以下映射的InstitutionsImplantations对象使用“ Null”,而不是全新的映射。
我的第一个解决方案是干净的,因为在2个“不同”的映射之间,缓存机制不起作用。 而且我没有找到一种简单的方法来禁用automapper中的此集合缓存机制!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.