0

From what I've read, AutoMapper is supposed to ignore getter-only properties. But with the configuration below the mapper throws an InvalidCastException due to this getter-only property

using AutoMapper;

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Model1, Model2>();
});

var mapper = new Mapper(config);

var m1 = new Model1 
{
    StringList = new List<string> { "String" }
};

var m2 = mapper.Map<Model2>(m1);


public class Model1
{
    public List<string> StringList { get; set; }

    public IEnumerable<object> Objects => StringList;
}

public class Model2
{
    public List<string> StringList { get; set; }

    public IEnumerable<object> Objects => StringList;
}

The Map() line throws this exception

AutoMapper.AutoMapperMappingException: 'Error mapping types.'

Inner Exception

InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.ICollection`1[System.Object]'.

cfmmark
  • 3
  • 1

1 Answers1

0

That doesn't apply to collections because they don't need a setter to be mapped, you can simply map into that collection.

See https://docs.automapper.org/en/latest/10.0-Upgrade-Guide.html#all-collections-are-mapped-by-default-even-if-they-have-no-setter

Lucian Bargaoanu
  • 3,336
  • 3
  • 14
  • 19
  • Thank you. However this page https://docs.automapper.org/en/latest/11.0-Upgrade-Guide.html#mapping-into-existing-collections says that if the collection is read-only (such as IEnumerable<>) the setter will be used to replace it and it won't try to map into the collection. This is a read only collection on a getter only property so I expected it to be left alone by AutoMapper – cfmmark Mar 02 '22 at 22:05
  • `Alternatively, you can remove the setter or set UseDestinationValue.` that means _exactly_ what I've said above. You're obviously misunderstading and your test proves it. – Lucian Bargaoanu Mar 03 '22 at 05:18