DbUpdateConcurrencyException当尝试用组合键更新表时

本文关键字:更新 组合 DbUpdateConcurrencyException | 更新日期: 2023-09-27 18:08:44

我使用的是Visual Studio 2015和MVC5。

我试着用这个代码建立一个编辑视图到一个表,我得到一个错误,我不能解决

        @Html.HiddenFor(model => model.GHE_CORRELATIVO)*@
    <div class="form-group">
        @Html.LabelFor(model=> model.COP_CORRELATIVO,"COP_CORRELATIVO")
        @Html.DropDownList("COP_CORRELATIVO", null, htmlAttributes: new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.GHE_DESCRIPCION, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.GHE_DESCRIPCION, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.GHE_DESCRIPCION, "", new { @class = "text-danger" })
        </div>
    </div>

dbupdateconcurrencyexception 当控制器接收到数据时。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "COP_CORRELATIVO,GHE_CORRELATIVO,GHE_DESCRIPCION")] GRUPO_HERRAMIENTA gRUPO_HERRAMIENTA)
{
    if (ModelState.IsValid)
    {
        db.Entry(gRUPO_HERRAMIENTA).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.COP_CORRELATIVO = new SelectList(db.CLASIFICACION_OPCION, "COP_CORRELATIVO", "COP_DESCRIPCION", gRUPO_HERRAMIENTA.COP_CORRELATIVO);
    return View(gRUPO_HERRAMIENTA);
}

我的表由两个pk组成,ghe_correlativo (own)和cop_correlativo (FK),脚手架只生成文本输入,但我需要用下拉字段编辑cop_correlativo字段。

模型结构:

   public partial class GRUPO_HERRAMIENTA
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public GRUPO_HERRAMIENTA()
        {
            this.PERFIL_INTRANET = new HashSet<PERFIL_INTRANET>();
        }
        public int COP_CORRELATIVO { get; set; }
        public int GHE_CORRELATIVO { get; set; }
        public string GHE_DESCRIPCION { get; set; }
        public virtual CLASIFICACION_OPCION CLASIFICACION_OPCION { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<PERFIL_INTRANET> PERFIL_INTRANET { get; set; }
    }

我做错了什么?

DbUpdateConcurrencyException当尝试用组合键更新表时

在调试中,确保在post操作中设置了所有参数,特别是COP_CORRELATIVO,这是主键。

对于测试目的,使用以下代码代替db.Entry(gRUPO_HERRAMIENTA).State = EntityState.Modified;:

db.GRUPO_HERRAMIENTAS.Attach(gRUPO_HERRAMIENTA); 
db.Entry(gRUPO_HERRAMIENTA).Property(i => i.COP_CORRELATIVO ).IsModified = true;
db.Entry(gRUPO_HERRAMIENTA).Property(i => i.GHE_CORRELATIVO ).IsModified = true;
db.Entry(gRUPO_HERRAMIENTA).Property(i => i.GHE_DESCRIPCION ).IsModified = true;