在我的应用程序中,我正在创建Identity Roles但是要确保不存在同名的其中一个。这是我试过的
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");
}
}
我知道它有错误,因为它是重复的,因为它在Role
不同时起作用,但为什么它似乎不使用if / else子句?
答案 0 :(得分:1)
你的问题是你没有将角色名称传递给Exists
函数,而是传递Role.ToString()
,它解析为类的名称,可能类似于Microsoft.AspNet.Identity.EntityFramework.IdentityRole
。相反,你应该传递Role.Name
,如下所示:
if (!roleManager.RoleExists(Role.Name))
{
_context.Roles.Add(Role);
_context.SaveChanges(); //error points here
return RedirectToAction("Index");
}