关于c#:以EF6代码优先的方式自定义角色的种子用户

Seed User with custom role in EF6 code-first

我在弄清楚如何首先使用EF6代码为我的MVC5应用程序植入更多用户和角色时遇到麻烦。 为了从update-database不能正常工作,从Configure.cs调试Seed方法,我编写了这个控制器,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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");调用中引发异常,提示"未找到UserID"? 这是一个屏幕截图,其中包含调试会话中的变量值:

enter image description here
问题是什么? 同样,完全相同的代码(将单词" basic"更改为" Admin")适用于使用角色为" admin"的Admin用户播种数据库。 为什么?

编辑编辑:我在这里先贴到下面的一个真实答案中移动了编辑。


正如评论所建议的那样,我将其发布为答案:

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