5

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?

Skullomania
  • 2,225
  • 2
  • 29
  • 65

1 Answers1

4

Your problem here is that you are not passing the role name into the Exists function, you are passing Role.ToString() which resolves to the name of the class, probably something like Microsoft.AspNet.Identity.EntityFramework.IdentityRole. Instead you should be passing Role.Name, like this:

if (!roleManager.RoleExists(Role.Name))
{
    _context.Roles.Add(Role);
    _context.SaveChanges(); //error points here
    return RedirectToAction("Index");
}
DavidG
  • 113,891
  • 12
  • 217
  • 223