Copy List Items Using AutoMapper

When I map the object to the default List Automapper property, sets the list object property of the destination object to the instance from the source object.

Is there any way for automapper to create a new list and copy the elements but not copy the list instance?

I would like to pass the following test:

var widget = new Widget
                {
                    Tags = new List<string> {"big", "bright"}
                };

Mapper.Reset();
Mapper.CreateMap<Widget, Widget>();

var widgetCopy = Mapper.Map<Widget, Widget>(widget);

CollectionAssert.Contains(widgetCopy.Tags, "big");
CollectionAssert.Contains(widgetCopy.Tags, "bright");
Assert.AreNotSame(widget.Tags, widgetCopy.Tags);

where the widget class is as follows:

class Widget
{
    public IList<string> Tags { get; set; }
}

Currently, the last statement fails because the two tag properties point to the same instance of the list. This is a problem when objects are stored in NHibernate.

+3
source share
2 answers
+3

, :

public static class DeepCopyExtensions
{
    public static List<T> DeepCopy<T>(this List<T> original)
    {
        lock(original) 
            return original.Select(AutoMapper.Mapper.Map<T, T>).ToList();
    }

    public static T DeepCopy<T>(this T original)
    {
        return AutoMapper.Mapper.Map<T, T>(original);
    }
}

AutoMapper :

Mapper.CreateMap<Widget, Widget>()
    .ForMember(
        dest => dest.Tags,
        opt => opt.MapFrom(src => src.Tags.DeepCopy()));
0

Source: https://habr.com/ru/post/1782265/


All Articles