I received this exception while debugging in VS 2012
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
//_dbSet declaration:
private readonly IDbSet<T> _dbSet;
//Method parameter
public virtual void Update(T entity)
//method fragment
public virtual void Update(T entity)
{
if (Entities == null) return;
var entry = Entities.Entry(entity);
switch (entry.State)
{
case EntityState.Modified:
var currentValues = entry.CurrentValues.Clone();
entry.Reload();
switch (entry.State)
{
case EntityState.Detached:
Entities.Entry(entry).State = EntityState.Modified;
break;
default:
entry.Reload();
entry.CurrentValues.SetValues(currentValues);
break;
}
break;
case EntityState.Detached:
_dbSet.Attach(entity); /*Here is the thing*/
entry.CurrentValues.SetValues(entity);
break;
}
Entities.Commit();
}
I have spent almost a week trying to solve optimistic concurrency with these patterns: DbFactory, Unit of Work, DI, Generic Repository, without getting results.