Home > database >  Automapper Map one class to two
Automapper Map one class to two

Time:11-20

I have an ASP.NET Core 6 app using Automapper 12.0.0 and I defined a mapper profile where I map one class to two different ones:

public class ModelMapper : AutoMapper.Profile
{
   public ModelMapper()
   {
      CreateMap<A, B1>().ReverseMap();
      CreateMap<A, B2>().ReverseMap();
   }
}

And then:

services.AddAutoMapper(typeof(ModelMapper));

When I try to map from B2 to A I get this error:

AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types: B2 -> A

Is there a way to set up AutoMapper to be able to map from A to B1 and to B2 and also from B1 to A and from B2 to A ?

CodePudding user response:

Maybe it was always me, but adding profiles this way never worked for me.

So I was always adding them this way:

    public static IServiceCollection AddAutoMapper(this IServiceCollection serviceCollection)
{
    serviceCollection.AddSingleton<IMapper>(factory =>
    {
        var config = new MapperConfiguration(x => x.AddProfiles(new Profile[]
        {
            new ModelMapper()
        }));

        return new Mapper(config);
    });

    return serviceCollection;
}

Also make sure that class A and B are matching with names, etc. If not then you would have to remove reverse map and add MapFrom

CodePudding user response:

I found the problem.

B1 had a property of class C1 B2 had a property of class C2 A had a property of class D

I forgot to map C1->D and C2->D

The error is misleading because it mentions B1, but the real issue was inside B1.

  • Related