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

ASP.NET Core EF调用PUT更新数据时报DbUpdateConcurrencyException如何解决

问题修复方案

错误原因

  • 你使用AutoMapper映射得到的WorkRoom实例没有设置主键WorkRoomId,你的WorkRoomDto中没有包含主键字段,导致EF执行更新时无法匹配到数据库中对应的记录,才会抛出DbUpdateConcurrencyException异常,提示预期影响1行实际影响0行。
  • 直接将Dto实例设置为EntityState.Modified报错是合理的:Dto不属于EF上下文注册的实体类型,无法被EF跟踪识别。

推荐修复方案

优先选择「先查询现有实体再更新字段」的方案,避免全字段覆盖的风险,也不需要手动处理实体状态:

public async Task<Response> PutWorkRooms(int id, WorkRoomDto workRoom)
{
    var respone = new Response();
    // 直接查询待更新的实体,同时完成存在性校验,不需要单独调用Any
    var existingWorkRoom = await _context.WorkRooms.FindAsync(id);
    if (existingWorkRoom == null)
    {
        respone.Status = false;
        respone.Message = "WorkRoomId no exist.";
        return respone;
    }
    var userId = await userManager.FindByIdAsync(workRoom.Id);
    if (userId == null)
    {
        respone.Status = false;
        respone.Message = "User not exist";
        return respone;
    }
    // 将Dto的字段映射到已被EF跟踪的现有实体上
    mapper.Map(workRoom, existingWorkRoom);
    // 不需要手动设置State,EF会自动识别实体字段变更
    await _context.SaveChangesAsync();
    respone.Status = true;
    respone.Message = "Successfully updated.";
    respone.Data = workRoom;
    return respone;
}

可选替代方案(不推荐)

如果你坚持要使用新建实体的方式更新,必须手动给新建实体赋值主键:

var newWorkRoom = mapper.Map<WorkRoomDto, WorkRoom>(workRoom);
// 手动补充主键,EF需要靠主键匹配更新记录
newWorkRoom.WorkRoomId = id;
_context.Entry(newWorkRoom).State = EntityState.Modified;
await _context.SaveChangesAsync();

注意:该方案会导致实体中未被Dto覆盖的字段被设置为默认值,存在数据丢失风险,仅适合实体所有字段都在Dto中包含的场景使用。

内容的提问来源于stack exchange,提问作者Đạt Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:39:05