0

Hi I'm getting following error while updating the record

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

Here's my Edit (Post) Action.

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

Is it becaus of I'm dealing with objects of Same Type within DB Context?

SRK
  • 70
  • 9

1 Answers1

1

The problem seems originated from EntityState.Modified before SaveChanges method, assuming hiringfactor is new entity as modification target:

db.Entry(hiringfactor).State = EntityState.Modified;

By convention, you can't re-attach a model once the entity has been loaded by the same key value. Try using this code right before SaveChanges:

db.Entry(parentFactor).CurrentValues.SetValues(hiringfactor);

Another way to set modified entity is using AsNoTracking when doing Find method like this:

HiringFactor parentFactor = db.HiringFactors.AsNoTracking().Find(parentId);

Similar issues:

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

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • `var parentFactor = db.HiringFactors.AsNoTracking().FirstOrDefault(hf => hf.Id == parentId);` This worked for me. Thank you @tetsuya-yamamoto – SRK Jun 13 '17 at 10:13