繁体   English   中英

在EF6代码优先的种子用户具有自定义角色

[英]Seed User with custom role in EF6 code-first

我首先使用EF6代码,无法确定如何将其他用户和角色植入我的MVC5应用程序中。 为了从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");抛出异常userManager.AddToRole(basicUser.Id, "basic"); 打电话说“找不到用户ID”? 以下是包含调试会话中的变量值的屏幕截图:

在此输入图像描述 问题是什么? 此外, 完全相同的代码 (更改“管理员”的“基本”一词)适用于使用角色“admin”中的Admin用户播种数据库。 为什么?

编辑编辑:移动编辑我发布在这里previoulsy下面的真实答案。

正如评论建议我将发布我的答案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM