c# - 库中的 AutoMapper 配置文件类 - AutoMapperMappingException : Missing type map configuration or unsupported mapping error

标签 c# asp.net-core automapper

我正在尝试在多层.Net Core Web API 中使用AutoMapper。这是层

  1. API - 所有 Controller (Web API)
  2. 业务 - 业务逻辑(库)
  3. 模型 - DTO 和 Automapper 配置文件(库)
  4. 数据 - EF 层(库)

在 Web API 中,我在启动时注入(inject)了所需的接口(interface)和具体类以及初始化 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)

最佳答案

您收到此错误是因为 AutoMapper 无法找到您的映射配置文件。

您的映射配置文件在“Models”程序集中定义,Startup 类位于“API”程序集中。

你有:

services.AddAutoMapper(typeof(Startup));

Automapper 将在定义了类型 Startup 的程序集中搜索配置文件。那不是您要找的。修改对 AddAutoMapper() 的调用并传递“Models”程序集中的类型。

关于c# - 库中的 AutoMapper 配置文件类 - AutoMapperMappingException : Missing type map configuration or unsupported mapping error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60868010/

相关文章:

c# - 如何使用 AutoMapper 动态映射内部类型

c# - AutoMapper - 为什么使用 Map 而不是 DynamicMap?

c# - 在浏览器中加载虚拟目录名称时,AcquireRequestState 中的 Session 为空,但在加载 Default.aspx 时不为空

c# - 实体类型的实例...无法跟踪,因为已跟踪具有相同键的该类型的另一个实例

c# - 我无法在 Visual Studio 2019 社区版本 16.6.2 中安装包 "Microsoft.VisualStudio.Web.CodeGeneration.Design"

c# - 升级到 EF Core 2.0 : System. InvalidOperationException: 属性 'Id' 不能配置为 'ValueGeneratedOnUpdate'

c# - 具有多对多和 IncludeMembers 的自动映射器

c# - iTextSharp 使用 AES 加密读取 PDF 抛出异常

c# - 如何检查是否在 Windows 中启用了 ClearType

c# - 使用 Swagger.NET,如何详细描述返回值?