0
votes

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();
}
1
Can you put a breakpoint on _context.SetModified(entity) and confirm that it is being called. - dave walker
Yes, it is being called. - Satyajit
Do you set the ID to a non-default value that is different for all entities after creation? - RHAD
finally, I solved this issue by creating a new instance of the context before saving the edit. - Satyajit

1 Answers

0
votes

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.