2

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]]```


Alex KeySmith
  • 16,657
  • 11
  • 74
  • 152
Smithy
  • 2,170
  • 6
  • 29
  • 61

1 Answers1

0

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.

Smithy
  • 2,170
  • 6
  • 29
  • 61
  • 2
    I think that they need the change name like ManuelMapper instead of AutoMapper – user3649317 Aug 16 '20 at 12:20
  • Hah! It's been a journey! In all fairness we're on AutoMapper 10 now and my code is quite simple these days: `cfg.CreateMap().ReverseMap();` – Smithy Aug 18 '20 at 08:46