You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用EF Core Update方法报Value cannot be null. (Parameter 'entity')如何解决

问题根因

你遇到的System.ArgumentNullException: Value cannot be null. (Parameter 'entity')报错,本质是仓储层Update方法接收到的clinicUser参数为null,该参数来自控制器中GetUserByEmail方法的返回值,触发null的场景有两类:

  • 当前请求的用户身份未正确携带邮箱声明,User.FindFirst(ClaimTypes.Name)?.Value返回null,导致查询条件为空,GetUserByEmail返回null
  • 邮箱取值正常,但对应用户的TemporaryRole字段值不为Doctor、或用户不存在,SingleOrDefaultAsync匹配不到结果返回null
修复方案

首先在控制器逻辑中增加空值校验,提前拦截异常场景并返回对应提示,修改后的控制器代码如下:

[HttpPut]
public async Task<ActionResult> UpdateDoctor(DoctorUpdateDTO doctorUpdateDTO)
{
    var email = User.FindFirst(ClaimTypes.Name)?.Value;
    // 校验用户身份的邮箱声明是否存在
    if (string.IsNullOrEmpty(email))
    {
        return Unauthorized("无法获取当前用户身份信息,请重新登录");
    }
    var user = await _userRepository.GetUserByEmail(email);
    // 校验查询到的用户是否存在、且身份为医生
    if (user == null)
    {
        return NotFound("未找到对应医生账号,请确认登录身份");
    }
    _mapper.Map(doctorUpdateDTO, user);
    _userRepository.Update(user);
    if (await _userRepository.SaveAllAsync()) return NoContent();
    return BadRequest("Failed to update Doctor Profile :(");
}

如果添加校验后触发了「未找到对应医生账号」的提示,可排查两点:

  1. 确认当前登录用户的TemporaryRole字段存储值是否为Doctor
  2. 确认ClaimTypes.Name对应的存储值是否确实为用户邮箱,若声明存储的是用户名而非邮箱,需要修改FindFirst的取值参数为对应声明类型

内容的提问来源于stack exchange,提问作者Kamil Wójcik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:06:03