Класс профиля AutoMapper в библиотеке - AutoMapperMappingException: отсутствует конфигурация карты типов или неподдерживаемая ошибка отображения - PullRequest
0 голосов
/ 26 марта 2020

Я пытаюсь использовать AutoMapper в многоуровневой. Net Core Web API. Вот слои

  1. API - все контроллеры (веб-API)
  2. Бизнес - бизнес логики c (библиотека)
  3. Модели - профили DTO и Automapper ( библиотека)
  4. Данные - слой EF (библиотека)

В Web API я ввел требуемый интерфейс и конкретный класс при запуске вместе с инициализацией AutoMapper, а также сослался на Models проект

  services.AddAutoMapper(typeof(Startup));
  services.AddDbContextPool<ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
  services.AddScoped<IStudent, Student.Business.Student>();

На уровне модели я создал класс профиля Automapper.

namespace Student.Models.Mapper
{
    public class StudentProfile : Profile
    {
        public StudentProfile()
        {
            CreateMap<Student, Entities.Student>().ReverseMap();
            CreateMap<StudentAddress, Entities.StudentAddress>().ReverseMap();
        }
    }
}

На бизнес-уровне

namespace Student.Business
{
    public class Student : BaseClass, IStudent
    {
        private readonly ApplicationContext _context;
        private readonly IMapper _mapper;


        public Student(ApplicationContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<Response<Models.Student>> CreateStudentAsync(Models.Student student)
        {
            var studentEntity = _mapper.Map<Entities.Student>(student);
            _context.Students.Add(studentEntity);
            await _context.SaveChangesAsync();
            var response = new Response<Models.Student>
            {
                Content = student
            };
            return response;
        }
    }
}

Я получаю следующая ошибка

AutoMapperMappingException: Missing type map configuration or unsupported mapping. Mapping types: Student -> Student Student.Models.Student -> Student.Entities.Student

lambda_method(Closure , Student , Student , ResolutionContext )
lambda_method(Closure , object , object , ResolutionContext )
AutoMapper.Mapper.Map<TDestination>(object source) in Mapper.cs
Student.Business.Student.CreateStudentAsync(Student student) in Student.cs

var studentEntity = _mapper.Map<Entities.Student>(student);

Student.Api.Controllers.StudentsController.CreateStudentAsync(Student student) in StudentsController.cs

return await _student.CreateStudentAsync(student);

lambda_method(Closure , object )
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

1 Ответ

1 голос
/ 26 марта 2020

Вы получаете эту ошибку, потому что AutoMapper не может найти ваши профили отображения.

Ваши профили отображения определены в сборке "Модели", а класс Startup находится в сборке "API".

У вас есть:

services.AddAutoMapper(typeof(Startup));

Automapper будет искать профили в сборке, в которой определен тип Startup. Это не то, что вы ищете. Измените вызов на AddAutoMapper() и передайте тип из сборки «Модели».

...