1

As per my requirement, I need to have a unique key for Email and UserName in UserIdentity. For which I have defined RequiredUniqueEmail=false like this in my startUp as stated here

services.AddIdentity<UserIdentity<string>, UserIdentityRole>(options => {
    options.User.RequireUniqueEmail = false; 
})
.AddEntityFrameworkStores<AdminIdentityDbContext>()
.AddDefaultTokenProviders();

And I am trying to validate and register in my application like this

var user = new TUser()
{
    Id = Guid.NewGuid().ToString(),
    EmployeeCode = model.EmployeeCode,
    UserName = model.UserName,
    Email = model.Email,
    UserTenures = new List<UserTenure>()
    {
        new UserTenure
        {
            TenureDateFrom = model.TenureDateFrom,
            TenureDateTo = model.TenureDateTo
        }
    }
 };
 bool combinationExists = await _userManager.Users
                .AnyAsync(x => x.UserName == model.UserName
                 && x.Email == model.Email);
 if (combinationExists)
 {
    List<IdentityError> identityErrors = new List<IdentityError>();
    IdentityError identityError = new IdentityError()
    {
        Code = "500",
        Description = "Combination of Username: " + model.UserName + " and Email:" + model.Email + " is duplicate"
    };
    identityErrors.Add(identityError);
    identityResult.Errors = identityErrors;
  }
  else
  {
     var result = await _userManager.CreateAsync(user, password);
     identityResult.IdentityId = user.Id;
     identityResult.Succeeded = result.Succeeded;
     identityResult.Errors = result.Errors;
     if (result.Succeeded)
     {
         // add user roles
         result = await AddUserRoles(user, model.Roles);
         //add user claims
         result = await AddUserClaim(user, model.Claims);
         await _signInManager.SignInAsync(user, isPersistent: false);
         
      }
   }
   return identityResult;

Now When I try to register the user which is unique in terms of UserName and Email, await _userManager.CreateAsync(user, password); throws an error stating DuplicateEmail. for Example I already have User having

UserName    NormalizedUserName      Email
1812PW10    1812PW10                financehq18@gmail.com

And trying to add new user with different UserName and same Email then, it is not getting registered and throwing an error "Email 'financehq18@gmail.com' is already taken." Where I am doing wrong? Is there any other way to fix such issues. I am sure there must be a solution to the problem. I wonder if I should keep investigating on the same direction Or perhaps, there's something else that needs to be overridden around Identity?

Iswar
  • 2,211
  • 11
  • 40
  • 65

0 Answers0