首页 新闻 会员 周边 捐助

按EF初始化策略DropCreateDatabaseIfModelChanges初始化数据库时,重写了Seed方法,但数据初始失败

0
悬赏园豆:10 [待解决问题]

初始化类

 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()); 
        }
BornReady的主页 BornReady | 初学一级 | 园豆:7
提问于:2015-10-26 09:18
< >
分享
所有回答(1)
0

有抛异常吗?

Firen | 园豆:5385 (大侠五级) | 2015-10-27 08:45

不太明白DropCreateDatabaseIfModelChanges,把数据库删掉后,在后面加上

var ctx=new ApplicationDbContext();
ctx.Database.Initialize(true);

运行程序会初始化数据库,但HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

抛出异常:在上下文中找不到 owin.Environment 项

支持(0) 反对(0) BornReady | 园豆:7 (初学一级) | 2015-10-27 09:14
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册