即使我传递了所需的变量,在编辑已存在的数据时也会出现DbUpdateConcurrencyException [英] DbUpdateConcurrencyException when editing data that already exists even though I pass the variables needed
问题描述
即使将 OrderID
传递给 DbUpdateConcurrencyException
错误> OrderItem 表单。它可以在创建
和删除
上使用,但是它一直让我无法进行编辑
。任何人都可以提出修复建议,或者如果我做错了事让我知道?
I'm getting the DbUpdateConcurrencyException
error even though I am passing the OrderID
to the OrderItem
form. It works on Create
and Delete
, but it keeps kicking me out for Edit
. Can anyone please suggest a fix or let me know if I'm doing something wrong?
我收到此并发异常错误
:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException未通过用户代码处理
HResult = -2146233087消息=存储更新,
插入或删除语句影响了意外的行数( 0)。
自加载实体以来,实体可能已被修改或删除。
请参见 http://go.microsoft.com/fwlink/?LinkId=472540 ,了解有关
理解和处理乐观并发异常的信息。
Source = EntityFramework StackTrace:System.Data.Entity.Internal.InternalContext.SaveChanges()中的
在System.Data.Entity.DbContext.SaveChanges()
在System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
在c中的HealthHabitat.Controllers.OrderItemController.Edit(OrderItem orderItem)在: \用户\路飞\桌面\HealthHabitat
V25\HealthHabitat\Controllers\OrderItemController.cs:line 97
在lambda_method(Closure,ControllerBase,Object [])
在System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase控制器,Object []参数)在System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext,IDictionary2 param) eters)
2
在System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext,ActionDescriptor actionDescriptor,IDictionary
参数)
在System.Web .Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
在System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult
asyncResult,ActionInvocation innerInvokeState)在System.Web.Mvc。 Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
1.End() System.Web.Mvc.Async.AsyncResultWrapper.End [TResult](IAsyncResult
asyncResult)
在System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase
asyncResult,对象标记)中的
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult)
,位于System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocati System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters上的onWithFilters.b__3d()
。<> c__DisplayClass46.b__3f()
InnerException:System.Data.Entity.Core.OptimisticConcurrencyException
HResult = -2146233087
消息=存储更新,插入或删除语句影响了意外的行数(0)。自加载实体以来,实体可能已被修改或
被删除。请参阅
http://go.microsoft.com/fwlink/?LinkId=472540 获取有关
理解和处理乐观并发异常的信息。
Source = EntityFramework
StackTrace:System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64
rowsAffected,UpdateCommand源)中的
在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(在System.Data.Entity.Core.Core.Mapping.Update.Internal.UpdateTranslator.Update()
) $ b在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update [T](T
noChangesResult,Func2 updateFunction)
1
在System.Data.Entity。 System.Data.Entity.Core.Objects.ObjectContext的Core.EntityClient.Internal.EntityAdapter.Update()
.System.Data.Entity.Core.Objects的b__35()
。 ObjectContext.ExecuteInTransaction [T](Func
函数,IDbExecutionStrategy执行策略,布尔值
startLocalTransaction,布尔值releaseConnectionOnSuccess )
在System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
选项,IDbExecutionStrategy执行策略,布尔值
startLocalTransaction)
在System.Data.Entity.Core。 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute [TResult](Func`1
操作)
在System.Data处为Objects.ObjectContext。<> c__DisplayClass2a.b__27()
。 Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions
选项,布尔型executeInExistingTransaction)
在System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
选项)
在System.Data.Entity.Internal.InternalContext.SaveChanges()处
InnerException:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException was unhandled by user code HResult=-2146233087 Message=Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
Source=EntityFramework StackTrace: at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at HealthHabitat.Controllers.OrderItemController.Edit(OrderItem orderItem) in c:\Users\Luffy\Desktop\HealthHabitat V25\HealthHabitat\Controllers\OrderItemController.cs:line 97 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase
1.End() at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f() InnerException: System.Data.Entity.Core.OptimisticConcurrencyException HResult=-2146233087 Message=Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions. Source=EntityFramework StackTrace: at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source) at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator ut) at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func2 updateFunction) at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func
1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Entity.Internal.InternalContext.SaveChanges() InnerException:
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "OrderItemID,OrderID,ItemID,Quantity")] OrderItem orderItem)
{
if (ModelState.IsValid)
{
db.Entry(orderItem).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", "Order", new { id = orderItem.OrderID });
}
ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name", orderItem.ItemID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", orderItem.OrderID);
return View(orderItem);
}
编辑视图:
@using (Html.BeginForm(new { OrderID = Model.OrderID }))
{
@Html.AntiForgeryToken()
<div class="panel panel-warning">
<div class="panel-heading">
<h4><i class="fa fa-edit"></i> Edit</h4>
</div>
<div class="panel-body">
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.OrderID)
<div class="form-group">
@Html.LabelFor(model => model.ItemID, "Item Name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ItemID", null, htmlAttributes: new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.ItemID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
</div>
</div>
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<a href="@Url.Action("Details", "Order", new { id = Model.OrderID }, null)" class="btn btn-default">Cancel</a>
<input type="submit" value="Save" class="btn btn-warning"/>
</div>
</div>
</div>
</div>
</div>
}
型号:
public class OrderItem
{
public int OrderItemID { get; set; }
public int OrderID { get; set; }
public int ItemID { get; set; }
[Range(1, 30, ErrorMessage = "{0} must be between {1} and {2}.")] // is this a row version?? I'm not sure, I'm kinda new to MVC
public int Quantity { get; set; }
public virtual Order Order { get; set; }
public virtual Item Item { get; set; }
}
获取编辑方法
// GET: OrderItem/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
OrderItem orderItem = db.OrderItems.Find(id);
if (orderItem == null)
{
return HttpNotFound();
}
ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name", orderItem.ItemID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", orderItem.OrderID);
return View(orderItem);
}
推荐答案
您必须放入RowVersion属性,然后将其发送到控制器:
You have to put the RowVersion property on the view, and send it to the controller:
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.OrderID)
@Html.HiddenFor(model => model.RowVersion)
Controller
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "OrderItemID,OrderID,ItemID,Quantity,RowVersion")] OrderItem orderItem)
{
if (ModelState.IsValid)
{
db.Entry(orderItem).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", "Order", new { id = orderItem.OrderID });
}
ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Name", orderItem.ItemID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", orderItem.OrderID);
return View(orderItem);
}
请注意,未在视图上修改的属性将为空。最好指定修改后的属性。
Be aware that properties which were not modified on view will be empty. It is better to specify the modified properties.
//db.Entry(orderItem).State = EntityState.Modified;
db.Entry(orderItem).Property(i => i.Quantity).IsModified = true;
//...
编辑
仅用于测试目的,而不是
Just for testing purposes, instead of
@using (Html.BeginForm(new { OrderID = Model.OrderID }))
尝试
@using (Html.BeginForm())
{
@Html.HiddenFor(i => i.OrderID)
}
编辑2
更改您的GET操作:
// GET: OrderItem/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
OrderItem orderItem = db.OrderItems.Find(id);
if (orderItem == null)
{
return HttpNotFound();
}
ViewBag.DDL_ItemID = db.Items.Select(i => new SelectListItem { Text = i.Name, Value = i.ItemID.ToString() }).ToList();
ViewBag.DDL_OrderID = db.Orders.Select(i => new SelectListItem { Text = i.OrderID.ToString(), Value = i.OrderID.ToString() }).ToList();
return View(orderItem);
}
请勿使用与a相同名称的ViewBag属性模型属性
更改视图中的DropDownList:
Change the DropDownList in your view:
@Html.DropDownListFor(i => i.ItemID, (IEnumerable<SelectListItem>)ViewBag.DDL_ItemID, new { @class = "form-control"})
在视图中,您将OrderItemID放在哪里?你必须把它放在那里。
In the view, where did you put the OrderItemID? You have to put it there.
这篇关于即使我传递了所需的变量,在编辑已存在的数据时也会出现DbUpdateConcurrencyException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!