由于某种原因,我在 AutoMapper 地图定义中使用的循环迭代次数超出了应有的次数。
地图定义:
Mapper.CreateMap<AdminGameEditModel, Game>()
.BeforeMap((s, d) =>
{
foreach (var platId in s.PlatformIDs)
{
Platform newPlat = _gameRepository.GetPlatform(platId);
d.Platforms.Add(newPlat);
}
})
.ForMember(dest => dest.BoxArtPath, opt => opt.Ignore())
.ForMember(dest => dest.IndexImagePath, opt => opt.Ignore())
.ForMember(dest => dest.Cons, opt => opt.MapFrom(src => String.Join("|", src.Cons)))
.ForMember(dest => dest.Pros, opt => opt.MapFrom(src => String.Join("|", src.Pros)))
.ForMember(dest => dest.LastModified, opt => opt.UseValue(DateTime.Now))
.ForMember(dest => dest.Platforms, opt => opt.Ignore());
foreach 在BeforeMap
由于某种原因,将多次迭代 s.PlatformIDs 数组。因此,例如,如果它包含两个值,我将得到六次或更多迭代,其中两个预期值重复。 PlatformID 是not定义为二维数组,调试器确认该数组仅包含应有的值,没有重复的集合。
我很困惑可能是什么原因造成的。
编辑:通过循环,我有以下断点 -
.BeforeMap((s, d) =>
{
foreach (var platId in s.PlatformIDs) // breakpoint 1
{
Platform newPlat = _gameRepository.GetPlatform(platId); // breakpoint 2
d.Platforms.Add(newPlat);
} // breakpoint 3
})
第一遍是正常的 - 断点 1 -> 断点 2 -> 断点 3。然后它将返回到 2,然后返回到 3,这是预期的。奇怪的是,它会跳回断点 1,并重新开始该过程。
我不确定是否有一个模式。两个数组值导致六次传递。一个数组值会产生四次传递。
编辑2:我的预感是对的 -BeforeMap
多次发射。
编辑3:问题仍然存在AfterMap
以及。每个映射该方法执行多次。