Search code examples
c#automapperautomapper-9

AutoMapper - Not working with generics after upgrade from v8 to v9


I have possibly and odd AutoMapper setup that was working before we updated to version 9.

We grab data from a database, wrap it in a generic object and then map it to a DTO:

        //build some models
        Domain test1 = new Domain() { Id = 1, Name = "Shaun" };
        Domain test2 = new Domain() { Id = 2, Name = "Dave" };

        //this is what I get from my API
        Revision<Domain> preMap = new Revision<Domain>() {
            RevisionNumber = 2,
            Items = new System.Collections.Generic.List<Domain> {
                test1, test2,
            }
        };

        //build mapper obj
        var config = new MapperConfiguration(cfg => {
            cfg.AddMaps(typeof(MyMaps).Assembly);
        });
        Mapper mapper = new Mapper(config);

        //map!
        var postMap = mapper.Map<Revision<DTOHistory<Dto>>>(preMap);


        Console.ReadLine();

Here is my revision and mapping profile classes:

public class Revision<MyItem> {
    public long RevisionNumber { get; set; }
    public List<MyItem> Items { get; set; }
}


public class MyMaps : AutoMapper.Profile {
    public MyMaps() {

        CreateAPI<Domain, Dto>();
    }

    private void CreateAPI<H, T>() {
        //I've tried fiddling with these to get a good config
        CreateMap<Revision<H>, Revision<DTOHistory<T>>>(MemberList.None);
            //.ForMember(dest => dest.Items, opt => opt.MapFrom(src => src.Items))
            //.ReverseMap();

        CreateMap<H, DTOHistory<T>>(MemberList.None);
            //.ReverseMap();
    }
}

I either end up with NULL DTOs Or I get an error similar to the below:


Mapping types:
Revision`1 -> Revision`1
AutoMapperTest.Revision`1[[AutoMapperTest.Domain, AutoMapperTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> AutoMapperTest.Revision`1[[AutoMapperTest.DTOHistory`1[[AutoMapperTest.Dto, AutoMapperTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], AutoMapperTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]```



Solution

  • Lucian Bargaoanu's comment shows the issue:

    http://docs.automapper.org/en/latest/9.0-Upgrade-Guide.html

    AutoMapper no longer creates maps automatically (CreateMissingTypeMaps and conventions) You will need to explicitly configure maps, manually or using reflection. Also consider attribute mapping.

    To fix I needed to go through each of the navigation properties and create a map for each type in the chain.