0

When I upgraded to Automapper 5.1.1, mapping of collections that are defined with readonly properties stopped to work (this works perfectly fine using Automapper 4.2.1)

Here is a sample code that you can try using both versions of Automapper to verify the behavior change. With automapper 5.1.1 result.MyList has zero elements.

class TestAutomapper
{
    public static void Test()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Test, TestDto>();                
        });
        var test = new Test();
        test.MyList.Add(1);

        var result= Mapper.Map<TestDto>(test);
    }
}

public class Test
{
    public List<int> MyList { get; } = new List<int>();
}

public class TestDto
{
    public List<int> MyList { get; } = new List<int>();
}

How can I get the map to work correctly using Automapper 5.1.1?

kizilsu
  • 431
  • 3
  • 13
Marcos
  • 151
  • 1
  • 9

1 Answers1

2

With the version 4.2.1, it wasn't working for us. It's weird that it was working for you in 4.2.1.

To make it worked with AutoMapper 4.2.1 we had to explicitly to tell how to map the original collection to the destination one.

CreateMap.Map<TestDto, Test>()
      .ForMember(x => x.MyList, opt => opt.MapFrom(y => y.MyList));
Roman
  • 4,922
  • 3
  • 22
  • 31
  • 1
    Yes, properties without setters are ignored by default, that's why you need the MapFrom. But you also need UseDestinationValue (which used to be true, but no longer). [Existing destination](https://github.com/AutoMapper/AutoMapper/blob/859612d672a45c62f3cce5c8b236be796497c916/src/UnitTests/CollectionMapping.cs#L26) and [new destination](https://github.com/AutoMapper/AutoMapper/blob/859612d672a45c62f3cce5c8b236be796497c916/src/UnitTests/CollectionMapping.cs#L55). – Lucian Bargaoanu Aug 24 '17 at 16:00