In my application I am creating Identity Roles but want to make sure that one of the same name does not exist. Here is what I have tried
public ActionResult Create()
{
var Role = new IdentityRole();
return View(Role);
}
[HttpPost]
public ActionResult Create(IdentityRole Role)
{
var roleStore = new RoleStore<IdentityRole>(_context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
if (!roleManager.RoleExists(Role.ToString()))
{
_context.Roles.Add(Role);
_context.SaveChanges(); //error points here
return RedirectToAction("Index");
}
else
{
TempData["message"] = "This role already exists. Please check your roles and try again";
return RedirectToAction("Index");
}
}
I know it errors out because it is a duplicate, since it works when the Role
is different, but why does it seem not use the if/else clause?