为什么即使存在于数据库中,角色也显示为"不存在"(asp.net mvc)

ibn*_*mza 2 c# asp.net-mvc asp.net-identity

我正在尝试在注册用户时将用户添加到角色中,因此我将角色播种并使用以下代码在migrations.cs类中更新数据库

        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));
            }
        }
Run Code Online (Sandbox Code Playgroud)

我试图将roleNames提取到我的accountcontroller类的下拉列表中

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);
}
Run Code Online (Sandbox Code Playgroud)

但是,调试器此时显示错误

UserManager.AddToRole(user.Id,model.Roleid); 角色bec759ac-55ca-40f0-a8b8-00de314dd2b3不存在.

但是这个角色存在于数据库中,所以我对问题是什么感到困惑 在此输入图像描述

Chr*_*att 5

第二个参数是字符串角色,而"Reviewer" 不是角色的id.这是错误的,因为字面上没有与NameGUID相等的角色.

请参阅:https://msdn.microsoft.com/en-us/library/dn497483(v = vs.108).aspx