Search code examples
c#tuplesmappingautomapperopen-generics

Using open generics with tuples is not working in AutoMapper 10


I have the following two POCOs:

private class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

private class PersonDto
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Then I defined two people:

private readonly Person _person1 = new Person
{
    Name = "Steve",
    Age = 20
};

private readonly Person _person2 = new Person
{
    Name = "Alex",
    Age = 45
};

Here is the code I tried to execute:

var mapper = new MapperConfiguration(m =>
{
    m.CreateMap<Person, PersonDto>().ReverseMap();
    m.CreateMap(typeof(Tuple<>), typeof(Tuple<>)).ReverseMap();
}).CreateMapper();

var tuple = Tuple.Create(_person1, _person2);
var mappedTuple = mapper.Map<Tuple<PersonDto, PersonDto>>(tuple);

On execution, I get an AutoMapperMappingException saying I am missing a type map configuration or the mapping is unsupported. My hope was that I could leverage the open generics feature and not have to register every Tuple version. If I explicitly do this, then everything works fine. Am I missing anything?

I am using AutoMapper v10.


Solution

  • It's because you did not specfied the generics of Tuple

    var mapper = new MapperConfiguration(m =>
    {
        m.CreateMap<Person, PersonDto>().ReverseMap();
        m.CreateMap(typeof(Tuple<Person, Person>), typeof(Tuple<PerdonDto,PersonDto>)).ReverseMap();
    }).CreateMapper();
    
    var tuple = Tuple.Create(_person1, _person2);
    var mappedTuple = mapper.Map<Tuple<PersonDto, PersonDto>>(tuple);
    

    Edit

    the right thing to do is:

    var mapper = new MapperConfiguration(m =>
        {
            m.CreateMap<Person, PersonDto>().ReverseMap();
            m.CreateMap(typeof(Tuple<,>), typeof(Tuple<,>)).ReverseMap();
        }).CreateMapper();
        
        var tuple = Tuple.Create(_person1, _person2);
        var mappedTuple = mapper.Map<Tuple<PersonDto, PersonDto>>(tuple);