• 记录在EF Core级联更新时出现的错误The database operation was expected to affect 1 row(s), but actually affected 0 row(s) (低级错误导致)


    错误提示:The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

    需求很简单,我有一个主表Module 模块表,有一个子表Menu菜单,我想要通过Module实体级联更新Menu表,Menu对象由前端直接传值给我

    代码如下:

    接口代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    [HttpPut]
           public void HttpPut()
           {
               Module module = _context.modules.Include(x => x.List).FirstOrDefault(x => x.Guid == Guid.Parse("1e8c7053-8323-4438-af75-94afabeb9d7e"));
               module.List.Clear();
               var menu = new Menu { Name = "345", Guid = Guid.NewGuid() };
               module.List.Add(menu);
               _context.SaveChanges();
           }

      实体代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    [Table("Menu")]
       public class Menu
       {
           [Key]
           public Guid Guid { get; set; }
     
           public Module Module { get; set; }
           public string Name { get; set; }
       }
     [Table("Module")]<br>
       public class Module
       {
           public Module()
           {
               List = new List<Menu>();
           }
           [Key]
           public Guid Guid { get; set; }
           public string Name { get; set; }
     
           [ConcurrencyCheck]
           public List<Menu> List { get; set; }
       }

      看似平平无常的代码,却一直提示了出错,搜索了一些相关的文章,也没有找的对应的解决方案,最后在官方文档中找到了对应的例子

    官方示例代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    using (var context = new BloggingContext())
    {
        var blog = context.Blogs.Include(b => b.Posts).First();
        var post = new Post { Title = "Intro to EF Core" };
     
        blog.Posts.Add(post);
        context.SaveChanges();
    }

      感觉和自己写的也是差不多,最后仔细发现原来自己在新增Menu的时候给主键赋值了,所以EF会判定你这条数据是去更新的,所以提示匹配到了0行数据,最后把主键的赋值去掉就可以保存成功了

  • 相关阅读:
    群狼调研(长沙医院满意度调查)|如何做医疗服务满意度调查
    用户管理【MySQL】
    雷达图应该如何去绘制?
    项目实战4: 基于 SpringBoot 的超市账单管理系统
    【前端设计模式】之适配器模式
    设计模式简要介绍
    从零开始搭建React+TypeScript+webpack开发环境-性能优化
    实现支付宝订单状态查询_大数据培训
    基于java雪花算法生成long类型无序ID实现
    HP电脑主机清除BIOS密码
  • 原文地址:https://www.cnblogs.com/wuyongfu/p/16270454.html