加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 没有其他用户的DB上的DbUpdateConcurrencyExcept

发布时间:2020-12-16 09:19:45 所属栏目:asp.Net 来源:网络整理
导读:MVC / EF新手…我的MVC Web应用程序是首先使用数据库模型中的代码创建的,因为我已经有了数据库(SQLExpress)… 当我尝试将记录更新到数据库时,我收到以下错误: Store update,insert,or delete statement affected an unexpected number of rows (0). Entitie
MVC / EF新手…我的MVC Web应用程序是首先使用数据库模型中的代码创建的,因为我已经有了数据库(SQLExpress)…

当我尝试将记录更新到数据库时,我收到以下错误:

Store update,insert,or delete statement affected an unexpected
number of rows (0). Entities may have been modified or deleted since
entities were loaded

使用从数据库实体框架模型首先使用代码生成的标准代码时出现此错误.很奇怪,因为我正在使用一台其他人无法访问的独立机器.

这是失败的代码:

if (ModelState.IsValid)
{
    db.Entry(tblPropGroup).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}

所以我写了下面的工作,一段时间完美无缺:

if (ModelState.IsValid)
{
db.Entry(_Prop).State = EntityState.Modified;
bool saveFailed;
do
{
 saveFailed = false;
 try
 {
 db.SaveChanges();
 }
 catch (DbUpdateConcurrencyException ex)
 {
 saveFailed = true;
 // Update original values from the database 
 var entry = ex.Entries.Single();
 entry.OriginalValues.SetValues(entry.GetDatabaseValues());
 }
} while (saveFailed);

谁能解释为什么db.SaveChanges在没有其他用户的数据库上导致DbUpdateConcurrencyException?如果我对数据进行任何更改,则没有任何区别.我有22个不同的表,我可以在这个程序中访问,如果没有这个解决方法,大约一半不会工作.

解决方法

我怀疑这与数据库上下文相关的竞争条件有关.

以下是一些答案:
side-effect of a feature called optimistic concurrency

Store update,or delete statement affected an unexpected number of rows (0) EntityFramework

这可能有所帮助.

最好使用:

using(DBContext context = new DBContext())
{
    //Entity code
}

处理您的上下文.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读