Sergiy
Sergiy

Reputation: 1972

ASP.NET Identity: attempting to add user with existing ID

ASP.NET Identity version 1.0

What is the default behavior of UserManager.CreateAsync(user, password) method call if we are trying to add an user with ID already existing in database?

I'm asking because some time ago the following line of code

IdentityResult result = await UserManager.CreateAsync(user, password);

returned an IdentityResult object with not empty Errors list saying something like "User with ID [ID] already exists".

But now (we didn't do much changes since that) we've got an exception when attempting to insert new user record in the database. In both cases UserManager.CreateAsync calls FindByNameAsync in our IUserStore implementation and that method finds and returns a correct User object.

How can I see the internal implementation of UserManager.CreateAsync method? Does it check new User object for existence before calling CreateAsync of IUserStore? I guess it does (since it calls FindByNameAsync but it seems it does not consider found User object as "existing".

Upvotes: 0

Views: 2117

Answers (1)

Sergiy
Sergiy

Reputation: 1972

I've found the answer using DotPeek (thanks trailmax for his suggestion). Yes, UserManager.CreateAsync makes validation (via UserValidator class) and the validator (among other conditions) has the following piece of code:

    TUser owner = await this.Manager.FindByNameAsync(user.UserName);
    if ((object) owner != null && owner.Id != user.Id)
      errors.Add(...);

So, as we see it checks if the user with this UserName already exists BUT the error is thrown only if the Id of that user differs from the Id of User object we are trying to create.

Since we generated Id before insertion and it actually equals to User's email - that caused the problem. The solution is simple: it's better to generate user's Id right before it's inserted into database.

Upvotes: 1

Related Questions