Reputation: 544
I have this code, but I get exception
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
in the else part.
public int AddOrUpdateEntity<T>(T entity) where T : class , IEntity
{
int numberOfobjectsWritten = 0;
using (DalContext dbContext = new DalContext())
{
//If Id == 0 it means it's a new entity in Db and needs to be added
dbContext.Entry<T>(entity).State = entity.Id == 0 ?
EntityState.Added :
EntityState.Modified;
numberOfobjectsWritten = dbContext.SaveChanges();
}
}
Upvotes: 1
Views: 4817
Reputation: 364289
This exception means that there is a duplicate entity with the same key already tracked by the context. Each entity can be tracked by the context only once. If you try to attach another instance of the same entity (it has the same key as already tracked instance) you will get this exception.
It means that another instance of the entity you are trying to update is already tracked by the context. Because attaching or adding is always applied on the whole object graph (it is applied on related entities accessed through navigation properties as well) the problematic entity doesn't have to necessarily be the one you are trying to modify but any of its relations.
You can try to use dbContext.ChangeTracker.Entries<T>().FirstOrDefault(e => e.Id == entity.Id)
to check if entity instance with the same key is already tracked.
Upvotes: 5