对于身份2种子数据库

编程入门 行业动态 更新时间:2024-10-26 00:24:33
本文介绍了对于身份2种子数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我碰到一个问题就来了与身份V2播种数据库。我从MVC5项目分离出来的IdentityModel到我的数据访问层,我安装EF迁移为好。所以我注释掉code这里面使用IdentityConfig.cs创建初始用户,并把code,看起来像这样我的种子数据库中

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"; 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); } }

现在,当我运行命令更新的数据库,我得到了一个错误

Now when I am running command update-database, I got an error

Value cannot be null. Parameter name: manager

它看起来像,我在code

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种子数据库

本文发布于:2023-11-05 04:44:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:种子   身份   数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!