Hopefully the following code snippet clear enough to explain the problem. _db
is an instance of DbContext
.
// this scenario is only for learning purpose
Author a = _db.Authors.Find(1831);
int id = a.AuthorId;
a = null;
Author stub = new Author { AuthorId = id };
_db.Remove(stub);
_db.SaveChanges();
The code above produces
'The instance of entity type 'Author' cannot be tracked because another instance with the same key value for {'AuthorId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
How to free a
from being tracked?
There are a variety of ways to do this, but I find this the most simple since you're trying to detach a specific entity.
_db.Entry(a).State = EntityState.Detached
As a plus it doesn't require changing any other code, including however you fetched the entity itself.
This one line makes it very clear of the intent. It also allows the following:
I dislike the idea of changing existing queries on a DbContext
when all I want to do is detach something.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments