【问题标题】:occurred using the connection to database 'ESCRestaurantDB' on server '.\SQLEXPRESS' [closed]使用与服务器“.\SQLEXPRESS”上的数据库“ESCRestaurantDB”的连接发生[关闭]
【发布时间】:2020-12-31 11:22:09
【问题描述】:
[HttpPost("add/{userId}")]
public async Task<IActionResult> Add(int userId, CategoryDto categoryDto)
{
    if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
        return Unauthorized();

    categoryDto.UserId = userId;


    var category = _mapper.Map<Category>(categoryDto);

    _repo.Add(category);

    if (await _unitOfWork.Complete())
        return Ok("Added successfully");

    throw new Exception("Adding Category Falid To Save");
}

这是我的控制器,我不知道该怎么办,为什么会显示这个错误。

using AutoMapper;
using QRmenu.API.Dtos;
using QRmenu.API.Models;

namespace QRmenu.API.Helpers
{
    public class AutoMapperProfiles : Profile
    {
        public AutoMapperProfiles()
        {
            CreateMap<User, UserForDetailedDto>();
            CreateMap<Item, ItemToReturnDto>()
               .ForMember(dest => dest.ItemImages, opt =>
               {
                   opt.MapFrom(src => src.ItemImages);
               });
                 
            CreateMap<Category, CategoryDto>();
        }
    }
}

这是我的 Automapper 代码。

我需要帮助来解决这个问题。

【问题讨论】:

  • “缺少类型映射配置或不支持的映射。” 对我来说似乎是不言而喻的。考虑到这看起来像是一个映射错误(即当您调用 mapper.Map&lt;TargetType&gt;(sourceObject) 时),包含该代码对您很有用。没有minimal reproducible example,我们无能为力。
  • 如果不言自明,帮忙
  • 嗯,它表示您尝试使用不受支持的映射对。它继续解释您已尝试将object 映射到Category。您没有为此定义映射。您还没有提供minimal reproducible example:您提供了映射配置,但没有提供此错误发生位置的示例。
  • 你现在可以显示我的代码吗
  • 显然我们需要查看 CategoryController 的 Add 方法中的代码。

标签: c# asp.net-core automapper


【解决方案1】:

现在我没有带开发环境的计算机来测试,但我觉得你忘了把 return 语句放在 opt lambda 函数中:

CreateMap() .ForMember(dest => dest.ItemImages, opt => {return opt.MapFrom(src => src.ItemImages); }

如果您可以粘贴更多关于如何调用地图功能的代码,我们可以为您提供帮助。

【讨论】:

  • 我粘贴了我的代码,你现在可以帮忙吗?
  • 使用 AutoMapper;使用 QRmenu.API.Dtos;使用 QRmenu.API.Models;命名空间 QRmenu.API.Helpers { public class AutoMapperProfiles : Profile { public AutoMapperProfiles() { CreateMap(); CreateMap() .ForMember(dest => dest.ItemImages, opt => opt.MapFrom(src => src.ItemImages); //去掉括号来修正 lambda 表达式 ); CreateMap(); } } }
  • 错误仍然存​​在,你现在可以显示我的控制器
  • 嗨 mohame mostfa,问题是您尝试将 categoryDto 映射到 Category var category = _mapper.Map(categoryDto);但是您的映射器配置是将类别映射到类别 DTO。 CreateMap 函数语法是 CreateMap 您可以修复添加: CreateMap();或者将地图配置改为 CreateMap().ReverseMap();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 2016-12-17
相关资源
最近更新 更多