Automapper returns reference to the same object when mapping sequences to arrays

只谈情不闲聊 提交于 2019-12-01 07:01:27

问题


I have an extension method for IEnumerable<T>, which maps sequence items and returns an array of clones:

public static class AutoMapperExtensions
{
    public static T[] MapToArray<T>(this IEnumerable<T> sequence)
    {
        return Mapper.Map<T[]>(sequence);
    }
}

Here's code sample, whose behavior is weird from my point:

        Mapper.CreateMap<SomeClass, SomeClass>();
        Mapper.AssertConfigurationIsValid();

        // clone list members and store them into array
        var list = new List<SomeClass>
        {
            new SomeClass { MyProperty = 1 },
            new SomeClass { MyProperty = 2 },
        };

        // works fine
        var array = list.MapToArray();

        // let's map array again
        var newArray = array.MapToArray();

        // ...and ensure, that new array was created;
        // this fails, because Automapper returns reference to the same array
        Debug.Assert(array != newArray); 

It seems to me, that last result is wrong. While I'm expecting, that mapper will create new array of clones, it just returns the reference to the same array.

Is this documented elsewhere or this is a bug?


回答1:


So this isn't a bug - when AutoMapper sees two objects that are assignable, it will simply assign them. If you want to override that behavior, create a map between the two collection types.



来源:https://stackoverflow.com/questions/28874357/automapper-returns-reference-to-the-same-object-when-mapping-sequences-to-arrays

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