身份 2 的种子数据库 [英] Seed database for Identity 2
问题描述
我在使用 Identity v2 为数据库做种时遇到了问题.我将 IdentityModel 从 MVC5 项目中分离到我的数据访问层,我也在其中设置了 EF 迁移.所以我注释掉了在IdentityConfig.cs"中使用的代码来创建初始用户并将代码放入我的种子数据库中,如下所示
I came across a problem for seeding the database with Identity v2. I separated out the IdentityModel from the MVC5 project to my Data Access Layer where I setup EF Migrations as well. So I commented out the code which use inside "IdentityConfig.cs" to create initial user and put the code inside my seed database that looks like this
protected override void Seed(Repository.DataContext.IdentityDb context)
{
// var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
// var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
var owinContext = new OwinContext();
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var roleManager = owinContext.Get<ApplicationRoleManager>();
const string name = "admin@admin.com";
const string password = "Admin@123456";
const string roleName = "Admin";
// //Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// // Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
现在,当我运行命令 update-database 时,出现错误
Now when I am running command update-database, I got an error
Value cannot be null.
Parameter name: manager
看起来,我在这两行代码中得到了 null
It looks like, I am getting null in these two lines of code
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var roleManager = owinContext.Get<ApplicationRoleManager>();
有什么建议吗?
推荐答案
这是避免使用 OWIN 上下文的方法:
This is the way to avoid using an OWIN context:
protected override void Seed(Repository.DataContext.IdentityDb context)
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = "sallen" };
userManager.Create(user, "password");
roleManager.Create(new IdentityRole { Name = "admin" });
userManager.AddToRole(user.Id, "admin");
}
这篇关于身份 2 的种子数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!