I have a generic repository:
public class GenericRepository<TEntity> : AbstractRepository<TEntity>, IRepository<TEntity> where TEntity : class
{
private DbContext _context;
[...]
public GenericRepository(DbContext context)
{
_context = context;
context.Configuration.AutoDetectChangesEnabled = true;
_dbSet = _context.Set<TEntity>();
}
[...]
public void SaveChanges()
{
_context.SaveChanges();
}
[...]
public void Add(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_dbSet.Add(entity);
}
[...]
public virtual void Update(TEntity entity)
{
_context.Entry(entity).State = EntityState.Modified;
}
In my controller, there is this code:
[HttpPost]
public ActionResult Edit(Project project)
{
if (ModelState.IsValid)
{
if (project.Id == 0)
{
ProjectRepository.Add(project);
}
else
{
ProjectRepository.Update(project);
}
ProjectRepository.SaveChanges();
[...]
Selecting and Inserting works fine, but Updating not: I get an InvalidOperationException (english translation of the german error message is “An object with the same key already exists in the Object State Manager. The Object State Manager can not track multiple objects with the same key.”).
I don’t understand that, because I’m the only user on my development machine, and I did not modify the record at another place.
Any idea what I’m doing wrong here?
Take a look at these answers:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
"An object with the same key already exists in the ObjectStateManager…" exception is thrown when setting an entity state to modified
Basically you need to do this:
Hopefully this helps.