Im new to Asp.net core 7 mvc.I created a custom identity and roles and i want to assign roles to users during registration. However the roles are not being assigned to the respective users as my ASPNetUserRole table is empty. Below is the code.The users are being saved to the system but they are not being assigned the roles.
[HttpPost]
public async Task<IActionResult> Register(RegisterVM model)
{
if (ModelState.IsValid)
{
ApplicationUser user = new()
{
UserName = model.UserName,
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Form = model.Form,
BirthDate = model.BirthDate ?? DateTime.MinValue
};
var result = await userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Assign the selected role to the user after creating the user
if (model.SelectedRoleId != null)
{
var role = await _roleManager.FindByIdAsync(model.SelectedRoleId);
if (role != null)
{
await userManager.AddToRoleAsync(user, role.Name);
}
}
await signInManager.SignInAsync(user, false);
return RedirectToAction("Index", "Home");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
model.RoleList = await GetRoleSelectListAsync();
return View(model);
}
ASPNETUSERROLETABLE
ASPNETUser table
Any help or advice is appreciated
New contributor
Dharvina R.K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.