This exception caused me to lose a bit more than expected 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 to read 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.
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:
var users = context.Users.AsNoTracking().ToList();
Hope you find this useful!