【问题标题】:Seed User with custom role in EF6 code-first在 EF6 代码优先中具有自定义角色的种子用户
【发布时间】:2015-05-06 18:47:52
【问题描述】:

我无法弄清楚如何将其他用户和角色植入我的 MVC5 应用程序,首先使用 EF6 代码。为了从Configure.cs调试Seed方法,因为update-database不工作,我写了这个控制器,

public ActionResult test() {

        var context = new ApplicationDbContext();
        var roleStore = new RoleStore<IdentityRole>(context);
        var roleManager = new RoleManager<IdentityRole>(roleStore);

        roleManager.Create(new IdentityRole { Name = "basic" });

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);

        var adminthere = context.Users.Any(n => n.UserName == "Admin");
        var basicthere = context.Users.Any(n => n.UserName == "Basic");

        // Create Dummy basic account
        if (!basicthere) {

            var basicUser = new ApplicationUser { UserName = "Basic" };
            userManager.Create(basicUser, "test");
            var _id = basicUser.Id;
            userManager.AddToRole(basicUser.Id, "basic");
        }
        return View();
    }

调试器在userManager.AddToRole(basicUser.Id, "basic"); 调用中抛出异常,提示“未找到用户ID”?这是一个截图,包括来自调试会话的变量值:

问题是什么?此外,完全相同的代码(将单词“basic”更改为“Admin”)适用于使用角色“admin”的Admin 用户为数据库播种。为什么?

编辑编辑:将我之前在这里发布的编辑移动到下面的真实答案。

【问题讨论】:

  • 不知道?也许您可以添加您的编辑作为答案? +1 以平衡问题,因为这个问题似乎是合理的。
  • 不知道为什么你也得到了反对票,但是是的,请发布你的编辑作为答案。就目前而言,没有其他人可以真正回答,因为您已经解决了问题,但是如果没有实际答案,这个问题将无限期地保留在未回答列表中。

标签: c# entity-framework authentication asp.net-mvc-5


【解决方案1】:

正如 cmets 建议的那样,我会将我的这个作为答案发布:

代码行userManager.Create(basicUser, "test"); 未成功 - 密码必须至少有 6 个字符。因此,虽然创建 basicUser ApplicationUser 实例有效(因此_id 不是null)我没有IdentityUser_id。在管理员上,它以前成功过 bc。我有一个不同的密码,我不想在这里发布......

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    相关资源
    最近更新 更多