I'm trying to add users to a role when registering a user so i seeded the roles and updated the database with the code below in the migrations.cs class
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
string[] roleNames = { "Admin", "Reviewer", "User" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
i tried to fetch the roleNames into a dropdownlist in my accountcontroller class
public ActionResult Register()
{
var model = new RegisterViewModel();
model.RolesList = new SelectList(_db.Roles, "Id", "Name");
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser()
{
UserName = model.UserName,
PortalUser = new PortalUser()
{
Email = model.Email,
UserName = model.UserName
}
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
UserManager.AddToRole(user.Id, model.Roleid);
return RedirectToAction("Index", "ApplicationReview");
}
else
{
AddErrors(result);
}
}
model.RolesList = new SelectList(_db.Roles, "Id", "Name");
// If we got this far, something failed, redisplay form
return View(model);
}
However the debugger showed an error at this point
UserManager.AddToRole(user.Id, model.Roleid); Role bec759ac-55ca-40f0-a8b8-00de314dd2b3 does not exist.
however this role exist in the database so i'm confused as to what the problem is