.NET Daily

ASP.NET Core and EF: The instance of entity type ‘User’ cannot be tracked

Introduction

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.


LATEST POSTS

Tips about Project Status Reports 05th October, 2017

Tips for Effective IT Projects Estimates 01st October, 2017

ASP.net

ASP.NET Core and EF: The instance of entity type ‘User’ cannot be tracked

Posted on .

This exception caused me to lose a bit more than two hours before finding the right solution. That happened even though the ASP.NET team already documented this Entity Framework behavior very well here but, you know, who has time for all that much documentation…

So, the full exception message is the following:

InvalidOperationException: The instance of entity type ‘User’ cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

This is exception is triggered when you query an entity that you later want to update it, but in a separate thread you query it again for various purposes.

In my particular case, I created an Edit page for my users and on the Save button, I did some validation for checking for duplicate email address of the user. So, I did a query to get the user info for saving then later, in the same context I queried again for it when I checked to see if the email address belongs to this user or to another one. When the SaveChanges() method was hit, the exception was triggered.

Solution

As mentioned as well on ASP.NET Website, all you have to do is to use the AsNoTracking() method when you query data data in the context where you don’t need to alter operations. In my case, I use it when I had to do the validation.
A sample code is the following:

Hope you find this useful!

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

There are no comments.

View Comments (0) ...
Navigation