Reputation: 13
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]'.
Upvotes: 1
Views: 831
Reputation: 3516
That doesn't apply to collections because they don't need a setter to be mapped, you can simply map into that collection.
Upvotes: 0