Entity Framework – Attaching an entity of type failed because another entity of the same type already has the same primary key value

This happened to me while updating model from viewmodel and changing its State to Modified.
Before save, I wanted to check model property values existing in the database.
The solution is to use AsNoTracking() with your query. This way newly retrieved object won’t be tracked by the context. That means context will not recognize that the object has the same Id as a primary key value.

if (entity.CustomerID > 0)
	Customer existing =  _context.Set<Customer>().AsNoTracking().Where(c => c.CustomerID == entity.CustomerID).FirstOrDefault();
	entity.PasswordHash = existing.PasswordHash;
	entity.PasswordSalt = existing.PasswordSalt;
	entity.rowguid = existing.rowguid;

Leave a Reply

Your email address will not be published. Required fields are marked *