0

I am constantly getting an error when I try to edit the same record for the second time using Entity Framework:

Attaching an entity of type 'DomainClasses.Item' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Code is very simple:

public void InsertOrUpdate(Item entity)
        {
        if (entity.Id == default(int)) 
            {
            _context.SetAdd(entity);
            }
        else        
            {
            _context.SetModified(entity);
            }

        _context.SaveChangesAsync();
}
Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
Satyajit
  • 1,971
  • 5
  • 28
  • 51
  • Can you put a breakpoint on `_context.SetModified(entity)` and confirm that it is being called. – dave walker Jul 03 '14 at 06:47
  • Yes, it is being called. – Satyajit Jul 06 '14 at 09:48
  • Do you set the ID to a non-default value that is different for all entities after creation? – RHAD Jul 12 '14 at 10:18
  • finally, I solved this issue by creating a new instance of the context before saving the edit. – Satyajit Jul 28 '14 at 08:20
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:33

1 Answers1

0

This error can happen when you've loaded an entity with tracking on so it's in the context already. Then you're trying to attach again which fails. If you load the entity AsNoTracking(), prior to calling InsertOrUpdate, the error should go away.