Extra iterations in a foreach in an AutoMapper map

放肆的年华 提交于 2019-12-19 16:27:47

问题


For some reason, a loop that I use in an AutoMapper map definition is iterating more than it should.

The map definition:

    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());

The foreach in BeforeMap will, for some reason, iterate over the s.PlatformIDs array multiple times. So, for example, if it contains two values, I'll get six or more iterations, with the two expected values repeating. The PlatformIDs are not defined as a two dimensional array, and the debugger confirms that the array only contains the values it should, with no repeating sets.

I'm stumped as to what could be causing it.


EDIT: With the loop, I have the following breakpoints -

.BeforeMap((s, d) =>
{
    foreach (var platId in s.PlatformIDs) // breakpoint 1
    {
        Platform newPlat = _gameRepository.GetPlatform(platId); // breakpoint 2

        d.Platforms.Add(newPlat);
    } // breakpoint 3
})

The first pass is normal - breakpoint 1 -> breakpoint 2 -> breakpoint 3. It will then go back to 2, then to 3, which is expected. What's weird is that it will then jump back to breakpoint 1, and start the process over again.

I'm not sure if there's a pattern. Two array values results in six passes. One array value results in four passes.


EDIT 2: My hunch was right - BeforeMap is firing more than once.


EDIT 3: The problem persists in AfterMap as well. The method executes more than once per mapping.


回答1:


Appears to be a legit bug, judging by something similar: http://automapper.codeplex.com/workitem/6604. I've written it up as an issue on AutoMapper's GitHub, and have linked that issue to this question so the devs can see what I was attempting to do.



来源:https://stackoverflow.com/questions/6460177/extra-iterations-in-a-foreach-in-an-automapper-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!