初始化类
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { InitializeIdentityForEf(); base.Seed(context); } private void InitializeIdentityForEf() { var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>(); const string name = "admin@123.com"; const string password = "Admin@123456"; const string roleName = "Admin"; //如果没有Admin用户组则创建该组 var role = roleManager.FindByName(roleName); if (role == null) { role = new IdentityRole(roleName); var roleResult = roleManager.Create(role); } //如果没有admin@123.com用户则创建该用户 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); } //把admin@123.com用户添加到Admin用户组 var roleForUser = userManager.GetRoles(user.Id); if (!roleForUser.Contains(role.Name)) { var result = userManager.AddToRole(user.Id, role.Name); } } }
在程序启动的时候初始化
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer(new ApplicationDbInitializer()); }
有抛异常吗?
不太明白DropCreateDatabaseIfModelChanges,把数据库删掉后,在后面加上
var ctx=new ApplicationDbContext(); ctx.Database.Initialize(true);
运行程序会初始化数据库,但HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
抛出异常:在上下文中找不到 owin.Environment 项