.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

How to Deliver Accurate Project Status Reports 21st April, 2018

JIRA Workflow for Web Development Example: Simple and Effective 17th April, 2018

Microsoft 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 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.

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:

var users = context.Users.AsNoTracking().ToList();

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.

Comments
  • user

    AUTHOR Artur

    Posted on 8:06 am February 7, 2018.
    Reply

    Thank you so much! You saved me a lot of time!))
    Have a nice day!

  • This site uses Akismet to reduce spam. Learn how your comment data is processed.

    View Comments (1) ...
    Navigation