编辑已存在的数据时DbUpdateConcurrencyException,即使我传递了所需的变量

时间:2015-09-04 19:07:30

标签: asp.net-mvc exception concurrency

即使我将DbUpdateConcurrencyException传递给OrderID表单,我也收到OrderItem错误。它适用于CreateDelete,但它一直在为Edit踢我。任何人都可以建议修复或让我知道我做错了什么?

我得到了Concurrency Exception Error

  

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException是   用户代码未处理HResult = -2146233087消息=存储更新,   insert或delete语句影响了意外的行数(0)。   自实体加载后,实体可能已被修改或删除。   有关的信息,请参阅http://go.microsoft.com/fwlink/?LinkId=472540   理解和处理乐观并发异常   Source = EntityFramework StackTrace:          在System.Data.Entity.Internal.InternalContext.SaveChanges()          在System.Data.Entity.Internal.LazyInternalContext.SaveChanges()          在System.Data.Entity.DbContext.SaveChanges()          在C:\ Users \ Luffy \ Desktop \ HealthHabitat中的HealthHabitat.Controllers.OrderItemController.Edit(OrderItem orderItem)   V25 \ HealthHabitat \ Controllers \ OrderItemController.cs:第97行          在lambda_method(Closure,ControllerBase,Object [])          在System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase控制器,Object []参数)          在System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext   controllerContext,IDictionary 2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2   参数)          在System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()          在System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult)   asyncResult,ActionInvocation innerInvokeState)          在System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase 1.End()          在System.Web.Mvc.Async.AsyncResultWrapper.End [TResult](IAsyncResult)   asyncResult,Object标签)          在System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult)   asyncResult)          在System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()          在System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters。&lt;&gt; c__DisplayClass46.b__3f()   InnerException:System.Data.Entity.Core.OptimisticConcurrencyException          的HResult = -2146233087          Message =存储更新,插入或删除语句影响了意外的行数(0)。实体可能已被修改或   自实体加载后删除。看到   http://go.microsoft.com/fwlink/?LinkId=472540了解有关的信息   理解和处理乐观并发异常。          来源=的EntityFramework          堆栈跟踪:               在System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64)   rowsAffected,UpdateCommand source)               在System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()               在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator)   UT)               在System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update [T](T   noChangesResult,Func 2 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)               在System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions)   options,IDbExecutionStrategy executionStrategy,Boolean   startLocalTransaction)               在System.Data.Entity.Core.Objects.ObjectContext。&lt;&gt; c__DisplayClass2a.b__27()               在System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute [TResult](Func`1   操作)               在System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions   options,Boolean executeInExistingTransaction)               在System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions   选项)               在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);
}

1 个答案:

答案 0 :(得分:1)

您必须将RowVersion属性放在视图上,然后将其发送到控制器:

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.OrderID)
@Html.HiddenFor(model => model.RowVersion)

控制器

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

请注意,未在视图上修改的属性将为空。最好指定修改后的属性。

//db.Entry(orderItem).State = EntityState.Modified;
db.Entry(orderItem).Property(i => i.Quantity).IsModified = true;
//...

修改

仅用于测试目的,而不是

@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);
}

不要使用与Model属性名称相同的ViewBag属性

更改视图中的DropDownList:

@Html.DropDownListFor(i => i.ItemID, (IEnumerable<SelectListItem>)ViewBag.DDL_ItemID, new { @class = "form-control"})

在视图中,您在哪里放置了OrderItemID?你必须把它放在那里。