【问题标题】:AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping in .NET COREAutoMapper.AutoMapperMappingException:.NET CORE 中缺少类型映射配置或不支持的映射
【发布时间】:2020-12-27 15:42:50
【问题描述】:

我在 .NET CORE 应用程序中使用 AutoMapper。我在 ConfigureServices.cs 方法文件中的 Startup.cs 中配置了 AutoMapper,如下所示:

public void ConfigureServices(IServiceCollection services)
        {

             /* Some Code */
            
            /* AutoMapper Configuration */
            services.AddAutoMapper(typeof(AutoMapperProfileConfiguration).GetType().Assembly);

            services.AddMvcCore();

             /* Some Code */
        }

AutoMapperProfileConfiguration 如下:

public class AutoMapperProfileConfiguration : Profile
    {
        public AutoMapperProfileConfiguration()
        {
            CreateMap<LoginRequestDto, Users>();
        }
    }

然后我在下面的课程中使用了这个映射器:

public LoginResponseDto CreateAnAccount(LoginRequestDto loginRequestDto)
        {
            var userInfo = _mapper.Map<Users>(loginRequestDto);
            userInfo.Id = Guid.NewGuid();
            _context.InsertItem<Users>(userInfo);
            var insertedUserDetails = _context.GetItemById<Users>(userInfo.Id);
            insertedUserDetails.Wait();
            return _mapper.Map<LoginResponseDto>(insertedUserDetails.Result);
        }

但是当我尝试将loginRequestDto 中存在的数据映射到Users 类时,它给了我以下异常:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
Object -> Users
System.Object -> NeighborhoodHelpers.UserMicroservice.Entities.Models.Users
   at lambda_method(Closure , Object , Users , ResolutionContext )
   at NeighborhoodHelpers.UserMicroservice.DataAccessProvider.UserDataAccess.UserDataAccess.CreateAnAccount(LoginRequestDto loginRequestDto) in D:\Gursimran\Hackathon2\NeighborhoodHelpers.UserMicroservice.API\NeighborhoodHelpers.UserMicroservice.DataAccessProvider\UserDataAccess\UserDataAccess.cs:line 29
   at NeighborhoodHelpers.UserMicroservice.Services.UserServices.UserService.CreateAnAccount(LoginRequestDto loginRequestDto) in D:\Gursimran\Hackathon2\NeighborhoodHelpers.UserMicroservice.API\NeighborhoodHelpers.UserMicroservice.Services\UserServices\UserService.cs:line 22
   at NeighborhoodHelpers.UserMicroservice.API.Controllers.LoginController.CreateAnAccount(LoginRequestDto loginRequestDto) in D:\Gursimran\Hackathon2\NeighborhoodHelpers.UserMicroservice.API\NeighborhoodHelpers.UserMicroservice.API\Controllers\LoginController.cs:line 34
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我正在使用 .NET Core 3.1。请帮我解决一下这个。我无法使用 AutoMapper 功能。

【问题讨论】:

  • 我的答案已更新
  • 您好,我的回答是否帮助您解决了您的问题?如果可以,请您接受作为回答吗?如果没有,请您跟进让我知道吗?参考:How to accept as answer.Thanks .

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

如下更改您的 Startup.cs:

services.AddAutoMapper(typeof(AutoMapperProfileConfiguration));

【讨论】:

    【解决方案2】:

    在您的代码中,AutoMapper 的配置看起来没有看到定义的配置文件,为了更正它,我建议使用 以下两个选项之一。

    选项 1: NuGet 包 AutoMapper

    1. 对于 Flexibility 和 Cleaner Code,定义一个扩展方法以添加当前的 AutoMapperProfileConfiguration 以及未来需要的许多其他方法。李>
    2. 打电话给Startup.cs

    CustomAutoMapper.cs:

    using AutoMapper;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace MyApp.CustomConfiguration
    {
        public static class CustomAutoMapper
        {
            public static void AddCustomConfiguredAutoMapper(this IServiceCollection services)
            {
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.AddProfile(new AutoMapperProfileConfiguration());
                });
    
                var mapper = config.CreateMapper();
    
                services.AddSingleton(mapper);
            }
        }
    }
    

    在 Startup.cs 中:

    services.AddCustomConfiguredAutoMapper();
    

    选项 2: 使用 AutoMapper.Extensions.Microsoft.DependencyInjection Nuget 包(我个人更喜欢使用两年以上,因为我在解决方案中使用了多个程序集并且这个包为 Profiles 提供了自动发现,因为它自动扫描任何继承自 AutoMapper 的 Profile 类的类的解决方案。

    只需在您的 Startup.cs 中:

    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    

    【讨论】:

    • @Simran Kaur 您的解决方案中有多少程序集? AutoMapper的包名和你安装的版本是什么?
    • 我已经安装了 Automapper 10.1.1 版
    • 您的解决方案中有多少个项目? Profile 类在哪里(在哪个程序集中?)@Simran Kaur
    【解决方案3】:

    查看 Users 和 LoginRequestDto 的属性可以更轻松地回答您的问题。因为从错误消息中可以理解,有些属性需要“忽略”,或者您正在做诸如将字典转换为列表之类的事情。

    如果你能展示你的课程,也许我们可以相应地安排以下行并解决问题。

    CreateMap<LoginRequestDto, Users>();
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2021-11-21
      • 2015-06-27
      • 1970-01-01
      • 2019-03-01
      • 2017-04-16
      • 2015-09-22
      • 1970-01-01
      相关资源
      最近更新 更多