EF Core instance of entity type cannot be tracked
See original GitHub issueI’ve been following the approaches proposed in this repo and the associated pluralsight course, and they have worked really well, but recently been getting the following exception thrown by EFCore:
“The instance of entity type ‘YourEntity’ cannot be tracked because another instance with the same key value for {‘Id’} 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.”
I have created a minimum example to demonstrate the issue (using EFCore inmemory and a Sqlite DB) here: https://github.com/robertlarkins/efcore-cannot-track-entity-issue
As far as I can determine it is related to static entities (such as Course in this repo, or Appointment Status in my linked repo), and it occurs when the context is holding an instance of AppointmentStatus pulled from the database, and the same AppointmentStatus is added to the context from the static AppointmentStatus reference in code. When trying to save the context to the database the above exception gets thrown.
This exception occurs on this line:
IEnumerable<EntityEntry> enumerationEntries = ChangeTracker.Entries()
.Where(x => EnumerationTypes.Contains(x.Entity.GetType()));
so it never gets to the point of trying to set the EntityState as unchanged.
Is this an issue you have come across before? I couldn’t find how this repo stops this occurring, hopefully I have just missed something, but if not, then I assume it could potentially happen within this repo as well. Alternatively should this issue be presented on the EFCore issue tracker?
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (1 by maintainers)

Top Related StackOverflow Question
Not sure why this is not working. Try adding lazy loading to your reference project, maybe that’s the difference here.
It’s impossible to make changes in CSharpFunctionalExtensions to avoid this issue, it is core to how EF keeps track of entities in its DbContext. As usual, it’s unnecessarily overcomplicated; it’s a solved problem in NHibernate.
FYI I opened a ticket for this here