CreateUserIdenityAsync returns "UserId not found" exception for custom IdentityUser
As you found out while debugging IdentityUser
has an Id
which in your case would represent the User's Id.
You need to remove the UserId
from your User
class, use the base Id
from IdentityUser
and rename the UserId
column in your custom User table to Id
.
Any properties you have in your User
class needs to also have a matching column in your user table in the database. If not then you will get the same error for properties that do not match.
That would mean Fullname
, Address
and ContactNumber
must have matching column names in the AspNetUsers
table or else you will get the same error for those properties as well.
You have both UserId
and Id
properties in your User
class - Id
is inherited from IdentityUser
. The problem is that you probably configured UserId
to be the primary key for User
.
The exception you get is thrown in ClaimsIdentityFactory.CreateAsync
method, on line 97 UserManager.GetSecurityStampAsync
. As you can see, user.Id
used for retrieving a security stamp.
If you look inside UserManager.GetSecurityStampAsync
you will see that the exception you get is thrown exactly here:
public virtual async Task<string> GetSecurityStampAsync(TKey userId)
{
ThrowIfDisposed();
var securityStore = GetSecurityStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
return await securityStore.GetSecurityStampAsync(user).WithCurrentCulture();
}
Thus, remove UserId
property from User
class and start using Id
(inherited from IdentityUser
) instead.
I faced exact same issue. After much of a head ache I could sort out the real problem. When you change data type of the Id property of User class to string, a Guid().ToString() is assigned to the Id property in the constructor and the same value is saved to the database and Identity retrieves the user details using that value.
However, if you changed the data type of the Id property to int and did not provide a value for that property in the constructor, the Identity still tries to retrieve the User details by using the default int value (0) this causes throws the message "System.InvalidOperationException: UserId not found".
I solved this by retrieving the value from the database by command.ExecuteScalar() and assign the value to user.Id. Hope this will help some one facing similar problem.