Automapper returns reference to the same object wh

2019-05-10 23:18发布

问题:

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.



标签: c# AutoMapper