cfmmark
cfmmark

Reputation: 13

Why does AutoMapper throw an InvalidCastException when mapping this getter-only property?

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

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

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.

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

Upvotes: 0

Related Questions