更新行时如何解决DbUpdateConcurrencyException? [英] How to solve DbUpdateConcurrencyException when updating a row?
问题描述
我正在针对ASP.NET MVC应用程序使用实体框架代码优先方法。提交以保存更改后,编辑了一行之后,我收到了http post方法的以下错误:
I'm using the entity framework code first approach for an ASP.NET MVC application. After editing a row when submitting for saving the change I'm getting the following error for the http post method:
$类型的异常b $ b'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException'
发生在EntityFramework.dll中,但未在用户代码中处理。
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code.
在db.SaveChanges()处遇到此错误。
This error is encountered at db.SaveChanges().
db.Entry<Project>(EditedProj).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
主代码:
[HttpGet]
public ActionResult Edit(int id)
{
using (var db = new ProjectContext())
{
return View(db.Projects.Find(id));
}
}
[HttpPost]
public ActionResult Edit(Project EditedProj)
{
using (var db = new ProjectContext())
{
db.Entry<Project>(EditedProj).State =
System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Projects");
}
}
推荐答案
I找到了答案。我没有传递Http Post操作方法的id值。
I have found the answer. I was not passing id value for Http Post action method.
如本链接
由DbContext引发的异常,当预期实体的SaveChanges将导致数据库更新,但实际上数据库中没有行受到影响。
Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected.
在我的情况下,上面的语句是正确的,因为我试图更新一行,但是没有id则没有行被更新。因此,例外。
In my case the above statement is true because I was trying to update a row but without id no row was updated. Hence, the exception.
可以使用包含id的隐藏输入元素来完成。下面的代码显示了如何在Edit.cshtml中进行操作–
It can be done using a hidden input element which contains the id. The code below shows how to do it in Edit.cshtml –
@using (Html.BeginForm("Edit", "Home", FormMethod.Post,
new { @class = "form-horizontal", role = "form" }))
{
@Html.HiddenFor(m => m.ProjectID)
//Other code … … …
}
这篇关于更新行时如何解决DbUpdateConcurrencyException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!