An object with the same key already exists in ObjectStateManager. ObjectStateManager cannot trace multiple objects with the same key.
When using EF to update data, the following error is reported:
An object with the same key already exists in ObjectStateManager. ObjectStateManager cannot trace multiple objects with the same key.
The reason is: two entities with the same key are not allowed in EF upper and lower versions.UpdateSome modifications are as follows:
public Product Update(Product item)
{ try
{ if (item == null)
{Throw new ArgumentException ("Product cannot be null "); }
var entry = db.Entry(item);
if (entry.State == EntityState.Detached)
{ var set = db.Set<Product>();
Product attachedProduct = set.Local.SingleOrDefault(p => p.Id == item.Id);
// If context tracing has been performed
if (attachedProduct != null)
{ var attachedEntry = db.Entry(attachedProduct);
attachedEntry.CurrentValues.SetValues(item);
}
Else // if not in the current context
{ entry.State = EntityState.Modified;
}
}
db.SaveChanges();
return item;
}
catch (Exception)
{ throw;
}
}
Solve the problem.
When updating data, you want to determine whether the modified User Group name already exists.
EntityContext will track the current object. If you use the current context to retrieve an object, you cannot create new on your own. You need to retrieve it from it, not new, when used, obtain the where id = your id from the context.
(Aspnet) injection with springnet, EF update error (ObjectStateManager already has an object with the same key)
Spring.net has never been used.