`UserManager.AddClaimAsync` keeps throwing duplicate PK exception for new claims

119 Views Asked by At

The following code snippet:

Claim claim = claims.FirstOrDefault(c => c.Type == "roles");
if (claim != null)
    await _userManager.RemoveClaimAsync(appUser, claim);
StringBuilder sb = new StringBuilder();
if (claim != null && !string.IsNullOrEmpty(claim.Value) && !claim.Value.Contains("buyer"))
    sb.Append($"{claim.Value} buyer");
else
    sb.Append("buyer");
try {
    await _userManager.AddClaimAsync(appUser, new Claim("roles", sb.ToString()));
} catch (Exception e) {
    _logger.LogError($"{nameof(CreateOrUpdateUser)} Exception! {e}");
}

keeps throwing the exception. I have checked the DB this user does NOT have roles claim at all. Exception: "23505: duplicate key value violates unique constraint \"PK_AspNetUserClaims\"\n\nDETAIL: Key (\"Id\")=(6532) already exists."

ASP.Net Core 7.0.105

0

There are 0 best solutions below