记录在EFCore级联更新时出现的错误Thedatabaseoperationwasexpectedtoaffect1row(s),butactuallyaffected0row(s)(低级错误导致)

博客 分享
0 126
张三
张三 2022-05-14 16:59:12
悬赏:0 积分 收藏

记录在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对象由前端直接传值给我

代码如下:

接口代码

 [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();        }

  实体代码

 [Table("Menu")]    public class Menu    {        [Key]        public Guid Guid { get; set; }        public Module Module { get; set; }        public string Name { get; set; }    }  [Table("Module")]
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; } }

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

官方示例代码如下:

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

posted @ 2022-05-14 16:16 吴先森 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    张三

    张三 (王者 段位)

    821 积分 (2)粉丝 (41)源码

     

    温馨提示

    亦奇源码

    最新会员