Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have following code to add or update the Entity object. finding the object by primary key, based on the response I am adding or updating the object.

Adding record works, but during update its giving this error message "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"

In my MSSQL database I have only one record.

var v = db.Envelopes.Find(model.ReportDate, model.Service); if (v == null) {     db.Envelopes.Add(model);     db.SaveChanges();     ViewBag.status = "Record Add successfully";     ModelState.Clear(); } else {     db.Entry(model).State = EntityState.Modified;     db.SaveChanges(); } 

How can I fix this error message?

like image 457
sfgroups Avatar asked Apr 15 '11 04:04

sfgroups


1 Answers

As mentioned by @anon you can't attach model once you loaded the entity with the same key. The changes must be applied to attached entity. Instead of this:

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

use this:

db.Entry(v).CurrentValues.SetValues(model); 
like image 196
Ladislav Mrnka Avatar answered Sep 18 '22 12:09

Ladislav Mrnka