在 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");
调用中抛出异常 "UserID not found"?这是包含调试会话中的变量值的屏幕截图:
问题是什么?此外,完全相同的代码(将单词"basic"更改为"Admin")适用于使用角色[=30]中的Admin
用户为数据库播种=].为什么?
编辑编辑:将我之前在此处发布的编辑移至下面的真实答案。
正如评论所建议的那样,我将 post 我的这个作为答案:
代码行 userManager.Create(basicUser, "test");
没有成功 - 密码必须至少有 6 个字符。因此,在创建 basicUser ApplicationUser
实例时(因此 _id
不是 null
),我没有那个 _id
的 IdentityUser
。在管理员上,它以前在公元前成功。我有一个不同的密码,我不想在这里 post ...
我无法确定如何首先使用 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");
调用中抛出异常 "UserID not found"?这是包含调试会话中的变量值的屏幕截图:
Admin
用户为数据库播种=].为什么?
编辑编辑:将我之前在此处发布的编辑移至下面的真实答案。
正如评论所建议的那样,我将 post 我的这个作为答案:
代码行 userManager.Create(basicUser, "test");
没有成功 - 密码必须至少有 6 个字符。因此,在创建 basicUser ApplicationUser
实例时(因此 _id
不是 null
),我没有那个 _id
的 IdentityUser
。在管理员上,它以前在公元前成功。我有一个不同的密码,我不想在这里 post ...