instance of entity type cannot be tracked because another instance with same key value is tracked [closed]

Your DB Context is being shared by multiple requests, meaning that the entity you’re editing has been tracked already.

This is likely because your repository service is a Singleton rather than Scoped, and so your DB Context is being reused with the entity being tracked when it’s pulled out, and then put back in to the same instance of the DB Context.

Instead of a Singleton repository, use a Scoped Repository, which means that a new instance will be created for each request. Likewise, you will also have a per-request DB Context.

When you register your service it will be using services.AddSingleton<..>

Change this to services.AddScoped<..>, when you inject it into your controller you will then get a new instance per request and your updates should work fine.

Leave a Comment