具有相同键错误的多个对象

时间:2017-06-09 11:03:07

标签: asp.net-mvc entity-framework object model dbcontext

您好,我在更新记录时遇到以下错误

  

ObjectStateManager中已存在具有相同键的对象。   ObjectStateManager无法跟踪具有相同对象的多个对象   键。

这是我的编辑(后)行动。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Type,Weightage,Description,ParentId")] HiringFactor hiringfactor)
    {
        if (ModelState.IsValid)
        {
            var childCount = 0;
            var indent = "";
            var parentId = hiringfactor.ParentId;

            HiringFactor parentFactor = db.HiringFactors.Find(parentId);
            if (parentFactor != null)
            {
                childCount = parentFactor.ChildHiringFactors.Count;
                indent = parentFactor.Indent + "." + (childCount + 1);
            }
            else
            {
                var parentCount = db.HiringFactors.Count(hf => (hf.ParentId == null || hf.ParentId == 0));
                indent = (parentCount + 1).ToString();
            }
            hiringfactor.Indent = indent;

            db.Entry(hiringfactor).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.ParentFactors = new SelectList(db.HiringFactors, "Id", "IndentName", hiringfactor.ParentId);
        return View(hiringfactor);
    }

是因为我在DB Context中处理相同类型的对象吗?

1 个答案:

答案 0 :(得分:1)

问题似乎源于.video方法之前的EntityState.Modified,假设SaveChanges是新实体作为修改目标:

hiringfactor

按照惯例,一旦实体被相同的键值加载,您就无法重新附加模型。请尝试在db.Entry(hiringfactor).State = EntityState.Modified; 之前使用此代码:

SaveChanges

设置修改后的实体的另一种方法是在执行db.Entry(parentFactor).CurrentValues.SetValues(hiringfactor); 方法时使用AsNoTracking

Find

类似问题:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key