首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AutoMapper on .Net Core 3.1

AutoMapper on .Net Core 3.1
EN

Stack Overflow用户
提问于 2020-03-12 19:39:10
回答 2查看 18.5K关注 0票数 3

在NetCore3.1应用程序中,我试图使用AutoMapper.Extensions.Microsoft.DependencyInjection 7。在解决方案中,我有3个项目:

  • 内容(开始项目)
  • 核心
  • 实体框架

在nuget安装之后,这是我的代码:

内容项目中的Startup.cs:

代码语言:javascript
复制
using AutoMapper;
using Project.Content.EntityFrameWork;
using Project.Content.Dto;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Project.Content
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            // Auto Mapper Configurations
            services.AddAutoMapper(typeof(AutoMapping));

            string connectionString = Configuration["ConnectionString:Default"];
            services.AddDbContext<ProjectContext>(options =>
        options.UseSqlServer(connectionString));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

内容项目中的AutoMapping.cs:

代码语言:javascript
复制
using AutoMapper;
using Project.Content.Core.Domain.Model;

namespace Project.Content.Dto
{
    class AutoMapping : Profile
    {
        public AutoMapping()
        {
            CreateMap<Exercise, ExerciseDto>();
            CreateMap<ExerciseDto, Exercise>();
        }
    }
}

这是控制器,我正在绘制地图:

代码语言:javascript
复制
using AutoMapper;
using Project.Content.EntityFrameWork;
using Project.Content.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Project.Content.Controllers
{
    [ApiController]
    [Route("/exercise")]
    public class ExercisesController : ControllerBase
    {
        private readonly ILogger<ExercisesController> _logger;
        private ProjectContext _dbContext;
        private IMapper _mapper;

        public ExercisesController(ILogger<ExercisesController> logger, ProjectContext dbContext, IMapper mapper)
        {
            _logger = logger;
            _dbContext = dbContext;
            _mapper = mapper;
        }

        [HttpGet("{id}")]
        public ExerciseDto GetById(int id)
        {

            var exercise =  _mapper.Map<ExerciseDto>(_dbContext.Exercises.Where(x => x.Id == id));
            return exercise;
        }
    }
}

在这个控制器中,当它试图映射对象时,它会显示错误:

AutoMapper.AutoMapperMappingException:缺少类型映射配置或不支持的映射。 映射类型: EntityQueryable1 -> ExerciseDto Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[Project.Content.Core.Domain.Model.Exercise,Project.Content.Core,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null] -> Project.Content.Dto.ExerciseDto at lambda_method(闭包,EntityQueryable`1 `1,ExerciseDto,ResolutionContext ) at lambda_method(闭包,对象,对象,( Project.Content.Controllers.ExercisesController.GetById(Int32 id)在C:\Projects\Project\Project.Content\Project.Content.Service\Controllers\ExercisesController.cs:line 44中的lambda_method(关闭,对象,Object[] )在Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object目标,Object[]参数)在Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper映射器,ObjectMethodExecutor执行器,对象控制器,( Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next,作用域和作用域,对象和状态,布尔& isCompleted)位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()的堆栈跟踪的结束--从以前在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next抛出异常的位置-在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed上下文中),Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()的作用域和范围、对象与状态、布尔& isCompleted) --从抛出异常的前一个位置开始的堆栈跟踪的结束--在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker调用程序、任务lastTask、状态下一步、作用域、对象状态,( Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker isCompleted) (在Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint端点),任务requestTask,ILogger记录器(在Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文))(在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-12 19:48:39

您正在试图映射IQueryable<T>,因为它使用延迟执行。在试图映射查询之前,您需要使用类似于ToList()ToListAsync()的东西来执行查询。

您还试图将集合映射到单个项。相反,您应该映射到集合。最终的结果是这样的

代码语言:javascript
复制
[HttpGet("{id}")]
public ExerciseDto GetById(int id)
{
  var exercises =  _dbContext.Exercises.Where(x => x.Id == id).ToList();
  return _mapper.Map<IEnumerable<ExerciseDto>>(exercises);
}

或者,您可以利用AutoMappers 可查询扩展来执行投影,这可能会带来更好的SQL性能,因为它只会查询所需的数据。这个看起来可能是这样的

代码语言:javascript
复制
[HttpGet("{id}")]
public ExerciseDto GetById(int id)
{
  return _mapper.ProjectTo<ExerciseDto>(_dbContext.Exercises.Where(x => x.Id == id)).ToList();
}

另外,如果您打算将此查询作为单个对象,或者如果它不存在,则可能使用FirstOrDefault而不是Where。此外,您还可以返回一个IActionResult来利用基本控制器结果,如NotFoundOk

票数 5
EN

Stack Overflow用户

发布于 2020-07-03 13:52:40

如果使用AutomapperPackage9.0.0或更高版本,则需要显式配置映射。

我解决了这一问题,将AutoMapper.Extensions.Microsoft.DependencyInjection降级为8.0.0,将AutoMapper降为6.0.0。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60660881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档