SRK
SRK

Reputation: 70

Multiple objects with the same key error

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?

Upvotes: 0

Views: 1175

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

Upvotes: 1

Related Questions