【问题标题】:Update method - Value cannot be null. (Parameter 'entity')更新方法 - 值不能为空。 (参数“实体”)
【发布时间】:2022-01-08 12:40:33
【问题描述】:

我有一个我无法解决的问题。 当我尝试更新数据库中名为“简介”的字段时,我从 API 收到此消息:

System.ArgumentNullException:值不能为空。 (参数“实体”) 在 Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T 值,字符串参数名称) 在 Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity 实体) 在 E:\Users\User\Desktop\Clinic\ClinicAPIv1\ClinicAPIv1\Data\UserRepository.cs:line 61 中的 ClinicAPIv1.Data.UserRepository.Update(ClinicUser ClinicUser) 在 E:\Users\User\Desktop\Clinic\ClinicAPIv1\ClinicAPIv1\Controllers\UsersController.cs:line 74 中的 ClinicAPIv1.Controllers.UsersController.UpdateDoctor(DoctorUpdateDTO doctorUpdateDTO) 在 lambda_method34(闭包,对象) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 执行器,对象控制器,对象 [] 参数) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Logged|12_1(ControllerActionInvoker 调用程序) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用程序,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed 上下文) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态&下一个,范围&范围,对象&状态,布尔& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker 调用者,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker 调用程序,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker 调用程序) 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点,任务 requestTask,ILogger 记录器) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文) 在 E:\Users\User\Desktop\Clinic\ClinicAPIv1\ClinicAPIv1\Middleware\ExceptionMiddleware.cs:line 30 中的 ClinicAPIv1.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context)

我了解问题在于我的存储库中的更新功能:

public void Update(ClinicUser clinicUser)
    {
        _context.Entry(clinicUser).State = EntityState.Modified;
    }

第 61 行是

_context.Entry(clinicUser).State = EntityState.Modified;

Controller Put 方法如下:

   [HttpPut]
public async Task<ActionResult> UpdateDoctor(DoctorUpdateDTO doctorUpdateDTO)
    {
        var email = User.FindFirst(ClaimTypes.Name)?.Value;
        var user = await _userRepository.GetUserByEmail(email);

        _mapper.Map(doctorUpdateDTO, user);

        _userRepository.Update(user);

        if (await _userRepository.SaveAllAsync()) return NoContent();

        return BadRequest("Failed to update Doctor Profile :(");
    }

第 74 行是

_userRepository.Update(user);

DoctorUpdateDTO:

public class DoctorUpdateDTO
{
    public string Introduction { get; set; }
}

映射器:

public class AutoMapperProfiles : Profile
{
    public AutoMapperProfiles()
    {
        CreateMap<ClinicUser, MemberDTO>()
            .ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(
                src => src.Photos.FirstOrDefault().Url));
        CreateMap<Photo, PhotoDTO>();
        CreateMap<DoctorUpdateDTO, ClinicUser>();
    }
}

通过电子邮件获取用户:

public async Task<ClinicUser> GetUserByEmail(string email)
    {
        return await _context.clinicUsers
            .Where(x => x.TemporaryRole == "Doctor")
            .Include(p => p.Photos)
            .SingleOrDefaultAsync(x => x.Email == email);
    }

诊所用户:

public class ClinicUser
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Specialization { get; set; }
    public string Introduction { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PhoneNumber { get; set; }
    [JsonIgnore]
    public ICollection<Photo> Photos { get; set; }
    public string TemporaryRole { get; set; }
}

请帮我解决问题

【问题讨论】:

  • 所以。当您对此进行调试时,此时对象状态不是您所期望的?
  • 您应该尝试在代码中包含单元测试。解决了很多这些问题。无论如何,检查 EntityState.Modified 以查看它是否返回 null。

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


【解决方案1】:

在您的 AutoMapperProfiles 中调用 CreateMap 之后链 ReverseMap。获取更多信息here

【讨论】:

  • 我尝试使用反向映射,但错误是一样的:(
  • 您能否用 ClinicUser 定义更新您的问题?
  • 完成,它是一个类女巫数据库字段
  • 如果您在 _userRepository.Update(user) 行中断,您的用户是否更新了 Introduction 值?尝试调试并查看映射是否正确完成。
  • 感谢您的帮助,感谢您,我解决了这个问题;))))))
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多