• 记录在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行数据,最后把主键的赋值去掉就可以保存成功了

  • 相关阅读:
    Windows 11 Manager v1.1.8 系统优化工具中文便携版
    【笔记】原油阳谋论
    关于软件交付质量度量标准 这里是一些建议
    管理系统权限篇
    Spark报错异常及解决
    Android Studio的笔记--HttpsURLConnection使用POST请求
    推荐系统介绍
    MyBatis核心配置文件
    曼孚科技入选IDC中国数据智能市场代表厂商
    使用Navicat对比多环境数据库数据差异和结构差异,以及自动DML和DDL脚本
  • 原文地址:https://www.cnblogs.com/wuyongfu/p/16270454.html