efcore: Static entities and cannot be tracked because another instance with the key value '{Id: }' is already being tracked.

I have an issue that I get when using static entities that exist in the database in my code. In a system using domain driven design we have static entities (we call them enum entities) where we have a lot of our business code attached to them. Problem is whenever we update an entity that has a related entity on of those enum entity we get the usual error

'The instance of entity type 'AccountStatus' cannot be tracked because another instance with the key value '{Id: 3}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.'

I have created a sample to demonstrate the issue. It can be found here at this repo. AccountStatus is the enum entity in this case. When we retrieve the user and try to activate the user accounts we get this error

If we load those entities from database we don’t get the error as the changetracker correctly identifies them. But whenever we are using the static instances we get this error. Since they are the same entities (same Ids) I don’t understand why changetracker behaves likes this. From what I read in other ORMs this behavior is covered. Is this something that can be fixed in EF Core as well?

EF Core version: 6.0.9 Database provider: Pomelo.EntityFrameworkCore.MySql 6.0.2 Target framework: .NET 6 Operating system: Windows 10 IDE: (e.g. Visual Studio 2019 16.3) VS2022 17.3.0

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 38 (13 by maintainers)

Most upvoted comments

Just to emphasize @pantonis ’ approach, I also use the “enum pattern with static values” approach. It is a well-known approach and is advocated on Pluralsight by Vladimir Khorikov

See this section in the EF Core 7.0 What’s New page.

Then as @ajcvickers mentioned you have to perform identity resolution yourself (so you don’t try to attach different instance with same key) through interceptor or outside of interceptor. Or you can try to write a materialization interceptor which rather than materializing new instance, returns your public static field value so there are no 2 instances with same key value.

You would need to perform identity resolution manually before attaching instances.