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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With