LPLN
LPLN

Reputation: 473

exception {'Id'} is already being tracked on ChangePasswordAsync()

I'm trying to update the password in identity and I've run into the following error:

The instance of entity type 'TblUsers' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

var changePasswordResult = await _userManager.ChangePasswordAsync(user: userData, currentPassword: Old, newPassword: New);

what am I do to solve this exception?

Upvotes: 1

Views: 1128

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239240

Based on the exception, userData is an instance of your Identity user class that you newed up, but you have previously queried that same user (which has the effect of adding to EF's object cache and change tracking). You're now trying to change the password using the instance that you newed up (which isn't tracked) instead of the instance pulled from the database (which is).

Long and short, if you're going to modify an entity, you should always use an instance pulled from the database to do so, not one you've newed up yourself. If the instance that was pulled from the database is around in this code, then use that. If it isn't, then pull it out of the context again (it will come from the object cache, so no additional query is necessary). Then, use that instance to change the password on.

Upvotes: 2

Related Questions