Error The instance of entity type ModalType cannot be tracked because another instance with the key value {id: 7656544} is already being tracked.

Question: How do you solve the Entity Framework Error that says: "Error The instance of entity type ModalType cannot be tracked because another instance with the key value {id: 7656544} is already being tracked. When attaching existing entities, ensure that only one entity with a given key value is attached.


Please Login to see the rest of the answer

Answer: Take a look around you class and find where you are referencing the same entity twice. If you are checking to see if the Entity Exists in the database by using the following code

MyEntity myEntity = _context.MyEntity.FirstOrDefault();
bool doesMyEntityExistInDatabase = _context.MyEntity.Any(a=>a.Id ==myEntity.Id);

//Then trying to modify MyEntity like this
myEntity.Name = "SomeNamesInHere";
_context.SaveChanges();

This might through an error saying the Entity is being tracked already. Instead do not reference the myEntity in any of the boolean code.

[Important]: When you load your database Modals into the Database Context without using AsNoTracking(), Entity Framework Core automatically Tracks All the Entities/Modals/POCO Classes. However in order to avoid the error "The instance of entity type ModalType cannot be tracked because another instance with the key value {id: 7656544} is already being tracked." in MVC AspNet 6 you need only to SaveChanges() and not attempt to Track the Entity you are trying to modify.

1. When you do _context.MyEntity.Update(NewEntity); you are telling EF Core 6 to track the Entity AGAIN!! which is why that error happens. Instead just Save the Changes.

2. If the Changes doesn't get commited or Saved to the Database, try to retrieve a fresh Entity from the Database Context then operate on that Entity by:

var MyEntity = _context.MyEntity.Where(a => a.id = id).FirstOrDefault();
MyEnitity.Name = "NameHere";

_context.SaveChanges();

That way the EF Core will not make a round trip to the Database to fetch MyEntity since it is already tracked it will retrieve it from the Momery Cache. 


Write an Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

Jack said:

Hey ErnesTech, thank you this helped alot.


© 2022 - ErnesTech - Privacy