Search code examples
asp.net-coreautomapper-5

How to configure and use automapper 5.1.1


I have been looking at this, trying to figure out how to get AutoMapper to work. This is what I had earlier

public class DomainToViewModelMappingProfile: Profile
{
    public DomainToViewModelMappingProfile()
    {
        Mapper.Initialize(cfg => cfg.CreateMap<Institution, InstitutionDataViewModel>()
        .ForMember(vm => vm.InstitutionID, map => map.MapFrom(s => s.InstitutionID))
        .ForMember(vm=>vm.InstituteName,map=>map.MapFrom(s=>s.InstituteName))
        .ForMember(vm=>vm.Circuit,map=>map.MapFrom(s=>s.AdministrativeStructure.AdminStructName))
        .ForMember(vm=>vm.Level,map=>map.MapFrom(s=>s.Level.LevelName))
        );
    }
}

Then followed by this

 public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
        {
            x.AddProfile<DomainToViewModelMappingProfile>();
        });
    }
}

Finally I have this in my startup.cs

// Automapper Configuration
        AutoMapperConfiguration.Configure();

My difficulty now is how to get this working in my controller and whether I am even on the right track. With all the varying information and different approaches all over the place i am terribly confused Thanks in advance


Solution

  • Your profile needs to call the non-static method. Change it from Mapper.CreateMap... to simply:

    public class DomainToViewModelMappingProfile : Profile
    {
        public DomainToViewModelMappingProfile()
        {
            CreateMap<Institution, InstitutionDataViewModel>()
            .ForMember(vm => vm.InstitutionID, map => map.MapFrom(s => s.InstitutionID))
            .ForMember(vm => vm.InstituteName, map => map.MapFrom(s => s.InstituteName))
            .ForMember(vm => vm.Circuit, map => map.MapFrom(s => s.AdministrativeStructure.AdminStructName))
            .ForMember(vm => vm.Level, map => map.MapFrom(s => s.Level.LevelName))
            );
        }
    }