Search code examples
.net-coreasp.net-core-mvcasp.net-identity

InvalidOperationException: Role testRole does not exist


I was trying to let the accountController to assign roles to each newly registered user automatically, so I've ended up doing something like this:

public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);
                //there is where the error is being raised.
                await _userManager.AddToRoleAsync(user, "testRole");

                if (result.Succeeded)
                {
                 //here goes some code
                 //have also adding this line of code inside this if stmt
                //await _userManager.AddToRoleAsync(user, "testRole");
                }
                AddErrors(result);
            }
            return View(model);
        }

I did what other posts on StackOverFlow recommended but, I keep having this error: InvalidOperationException: Role TESTROLE does not exist.

Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore+d__34.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Identity.UserManager+d__104.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.GetResult() WebApplication2.Controllers.AccountController+d__17.MoveNext() in AccountController.cs

Notes:

  • I was using PostgreSql on my project, so I've created a new project with MSSQL and ended up with the same error.
  • I've made sure that the testRole is being in the table AspNetRoles. So ,there's no problem with that either!

Solution

  • so testRole is exact name which would then get normalized to TESTROLE how was TestRole created? I say this because Identity looks for the normalized version. Exception is pretty clear that it doesn't exist in this case. Basically if you didn't use RoleManager then something is wrong with the way you created the role

    Another way to create the role would be using your database context and add in new roles that way but if you didn't use caps for the NormalizedName field entry then this is the error you will get