public static void EnsureSeedData(IServiceProvider serviceProvider) { //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data //4.dotnet run /seed Console.WriteLine("Seeding database..."); using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope()) { scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate(); { var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>(); context.Database.Migrate(); EnsureSeedData(context); } { var context = scope.ServiceProvider.GetService <ApplicationDbContext>(); context.Database.Migrate(); var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >(); var BlogCore_Users = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))); var BlogCore_Roles = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))); var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))); foreach (var item in BlogCore_Users) { if (item == null || item.uLoginName == null) { continue; } var userItem = userMgr.FindByNameAsync(item.uLoginName).Result; var rid = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == item.uID)?.RoleId; var rName = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name; if (userItem == null) { if (rid > 0 && !string.IsNullOrEmpty(rName)) { userItem = new ApplicationUser { UserName = item.uLoginName, LoginName = item.uRealName, sex = item.sex, age = item.age, birth = item.birth, addr = item.addr, tdIsDelete = item.tdIsDelete }; //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result; // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了 var result = userMgr.CreateAsync(userItem, "BlogIdp123$InitPwd").Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } result = userMgr.AddClaimsAsync(userItem, new Claim[] { new Claim(JwtClaimTypes.Name, item.uRealName), new Claim(JwtClaimTypes.Email, $"{item.uLoginName}@email.com"), new Claim(JwtClaimTypes.Role, rName) }).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表 } else { Console.WriteLine($"{item?.uLoginName} doesn't have a corresponding role."); } } else { Console.WriteLine($"{userItem?.UserName} already exists"); } } } } Console.WriteLine("Done seeding database."); Console.WriteLine(); }
internal static void EnsureSeedData(IServiceProvider serviceProvider) { //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data //4.dotnet run /seed Console.WriteLine("Seeding database..."); using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope()) { scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate(); { var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>(); context.Database.Migrate(); EnsureSeedData(context); } { var context = scope.ServiceProvider.GetService <AppIdentityDbContext>(); context.Database.Migrate(); var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >(); var roleMgr = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >(); var BlogCore_Users = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))); var BlogCore_Roles = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))); var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))); // 迁移【用户】信息 foreach (var item in BlogCore_Users) { if (item == null || item.uLoginName == null) { continue; } var userItem = userMgr.FindByNameAsync(item.uLoginName).Result; var userRoles = BlogCore_UserRoles.Where(d => d.UserId == item.uID).ToList(); //var rName = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name; if (userItem == null) { if (userRoles.Count > 0) { var applicationUserRole = new List <ApplicationUserRole>(); foreach (var userRoleItemS in userRoles) { applicationUserRole.Add(new ApplicationUserRole() { }); } userItem = new ApplicationUser { UserName = item.uLoginName, LoginName = item.uRealName, sex = item.sex, age = item.age, birth = item.birth, addr = item.addr, tdIsDelete = item.tdIsDelete, RealName = item.uRealName, }; //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result; // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了 var result = userMgr.CreateAsync(userItem, "BlogIdp123$InitPwd").Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } result = userMgr.AddClaimsAsync(userItem, new Claim[] { //new Claim(JwtClaimTypes.Name, item.uRealName), new Claim(JwtClaimTypes.Email, $"{item.uLoginName}@email.com"), //new Claim(JwtClaimTypes.Role, rName) }).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表 } else { Console.WriteLine($"{item?.uLoginName} doesn't have a corresponding role."); } } else { Console.WriteLine($"{userItem?.UserName} already exists"); } } // 迁移【角色】信息,Role信息统一在这里处理,Blog.Core 只负责读,不负责写 foreach (var item in BlogCore_Roles) { if (item == null || item.Name == null) { continue; } var roleModel = roleMgr.FindByNameAsync(item.Name).Result; if (roleModel == null) { roleModel = new ApplicationRole { Name = item.Name, Description = item.Description, IsDeleted = (bool)(item.IsDeleted), CreateBy = item.CreateBy, CreateId = item.CreateId, CreateTime = item.CreateTime, ModifyBy = item.ModifyBy, ModifyId = item.ModifyId, ModifyTime = item.ModifyTime, Enabled = item.Enabled, OrderSort = item.OrderSort, NormalizedName = item.Name, }; var result = roleMgr.CreateAsync(roleModel).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } } else { Console.WriteLine($"{roleModel?.Name} already exists"); } } } } Console.WriteLine("Done seeding database."); Console.WriteLine(); }
public static async Task SeedAsync(MyContext myContext) { try { //codefirst创建数据库 ,如果是第二次执行,注释掉即可 myContext.CreateTableByEntity(false, //typeof(Module), //typeof(ModulePermission), //typeof(OperateLog), //typeof(PasswordLib), //typeof(Permission), //typeof(Role), //typeof(RoleModulePermission), //typeof(sysUserInfo), //typeof(UserRole), //typeof(Topic), //typeof(TopicDetail), ////以下是业务表 //typeof(CustomInfo), //typeof(ExtraProjectInfo), //typeof(ExtraOtherProject), //typeof(Dictionary), //typeof(PartyAdvisoryInfo), //typeof(PartyBookInfo), //typeof(PartyDemands), typeof(GraduationStatistics) //typeof(ExcelMapToModel) ); //下面就是种子数据 #region CustomInfo if (!await myContext.Db.Queryable <CustomInfo>().AnyAsync()) { myContext.GetEntityDB <CustomInfo>().Insert( new CustomInfo { Name = "管理员", PhoneNumber = "158888888", Birthday = "11岁", AdvisoryTime = DateTime.Now, ScheduledDate = DateTime.Now, CreatedBy = "wangchao", UpdatedBy = "wangchao", CreateTime = DateTime.Now, UpdateTime = DateTime.Now, }); Console.WriteLine("Done seeding database."); Console.WriteLine(); } #endregion #region Module if (!await myContext.Db.Queryable <Module>().AnyAsync()) { myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module")))); Console.WriteLine("Table:Module created success!"); } else { Console.WriteLine("Table:Module already exists..."); } #endregion #region Permission if (!await myContext.Db.Queryable <Permission>().AnyAsync()) { myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission")))); Console.WriteLine("Table:Permission created success!"); } else { Console.WriteLine("Table:Permission already exists..."); } #endregion #region Role if (!await myContext.Db.Queryable <Role>().AnyAsync()) { myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")))); Console.WriteLine("Table:Role created success!"); } else { Console.WriteLine("Table:Role already exists..."); } #endregion #region RoleModulePermission if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync()) { myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission")))); Console.WriteLine("Table:RoleModulePermission created success!"); } else { Console.WriteLine("Table:RoleModulePermission already exists..."); } #endregion #region Topic if (!await myContext.Db.Queryable <Topic>().AnyAsync()) { myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic")))); Console.WriteLine("Table:Topic created success!"); } else { Console.WriteLine("Table:Topic already exists..."); } #endregion #region TopicDetail if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync()) { myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail")))); Console.WriteLine("Table:TopicDetail created success!"); } else { Console.WriteLine("Table:TopicDetail already exists..."); } #endregion #region UserRole if (!await myContext.Db.Queryable <UserRole>().AnyAsync()) { myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")))); Console.WriteLine("Table:UserRole created success!"); } else { Console.WriteLine("Table:UserRole already exists..."); } #endregion #region sysUserInfo if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync()) { myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")))); Console.WriteLine("Table:sysUserInfo created success!"); } else { Console.WriteLine("Table:sysUserInfo already exists..."); } #endregion Console.WriteLine("Done seeding database."); Console.WriteLine(); } catch (Exception ex) { throw new Exception("初始化种子数据失败" + ex.Message); } }
/// <summary> /// 异步添加种子数据 /// </summary> /// <param name="myContext"></param> /// <returns></returns> public static async Task SeedAsync(MyContext myContext) { try { // 如果生成过了,第二次,就不用再执行一遍了,注释掉该方法即可 // 自动创建数据库,注意版本是 sugar 5.x 版本的 myContext.Db.DbMaintenance.CreateDatabase(); // 创建表 myContext.CreateTableByEntity(false, typeof(Advertisement), typeof(BlogArticle), typeof(Guestbook), typeof(Module), typeof(ModulePermission), typeof(OperateLog), typeof(PasswordLib), typeof(Permission), typeof(Role), typeof(RoleModulePermission), typeof(sysUserInfo), typeof(Topic), typeof(TopicDetail), typeof(UserRole)); // 后期单独处理某些表 //myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo)); //myContext.Db.CodeFirst.InitTables(typeof(Permission)); //myContext.Db.CodeFirst.InitTables(typeof(Advertisement)); Console.WriteLine("Database:WMBlog created success!"); Console.WriteLine(); Console.WriteLine("Seeding database..."); #region BlogArticle if (!await myContext.Db.Queryable <BlogArticle>().AnyAsync()) { myContext.GetEntityDB <BlogArticle>().InsertRange(JsonHelper.ParseFormByJson <List <BlogArticle> >(GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle")))); Console.WriteLine("Table:BlogArticle created success!"); } else { Console.WriteLine("Table:BlogArticle already exists..."); } #endregion #region Module if (!await myContext.Db.Queryable <Module>().AnyAsync()) { myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module")))); Console.WriteLine("Table:Module created success!"); } else { Console.WriteLine("Table:Module already exists..."); } #endregion #region Permission if (!await myContext.Db.Queryable <Permission>().AnyAsync()) { myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission")))); Console.WriteLine("Table:Permission created success!"); } else { Console.WriteLine("Table:Permission already exists..."); } #endregion #region Role if (!await myContext.Db.Queryable <Role>().AnyAsync()) { myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")))); Console.WriteLine("Table:Role created success!"); } else { Console.WriteLine("Table:Role already exists..."); } #endregion #region RoleModulePermission if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync()) { myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission")))); Console.WriteLine("Table:RoleModulePermission created success!"); } else { Console.WriteLine("Table:RoleModulePermission already exists..."); } #endregion #region Topic if (!await myContext.Db.Queryable <Topic>().AnyAsync()) { myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic")))); Console.WriteLine("Table:Topic created success!"); } else { Console.WriteLine("Table:Topic already exists..."); } #endregion #region TopicDetail if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync()) { myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail")))); Console.WriteLine("Table:TopicDetail created success!"); } else { Console.WriteLine("Table:TopicDetail already exists..."); } #endregion #region UserRole if (!await myContext.Db.Queryable <UserRole>().AnyAsync()) { myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")))); Console.WriteLine("Table:UserRole created success!"); } else { Console.WriteLine("Table:UserRole already exists..."); } #endregion #region sysUserInfo if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync()) { myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")))); Console.WriteLine("Table:sysUserInfo created success!"); } else { Console.WriteLine("Table:sysUserInfo already exists..."); } #endregion Console.WriteLine("Done seeding database."); Console.WriteLine(); } catch (Exception ex) { throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message); } }
/// <summary> /// 异步添加种子数据 /// </summary> /// <param name="myContext"></param> /// <returns></returns> public static async Task SeedAsync(MyContext myContext) { try { // 如果生成过了,第二次,就不用再执行一遍了,注释掉该方法即可 #region 自动创建数据库暂停服务 // 自动创建数据库,注意版本是 sugar 5.x 版本的 // 注意:这里还是有些问题,比如使用mysql的话,如果通过这个方法创建空数据库,字符串不是utf8的,所以还是手动创建空的数据库吧,然后设置数据库为utf-8,我再和作者讨论一下。 // 但是使用SqlServer 和 Sqlite 好像没有这个问题。 //myContext.Db.DbMaintenance.CreateDatabase(); #endregion // 创建表 myContext.CreateTableByEntity(false, typeof(Advertisement), typeof(BlogArticle), typeof(Guestbook), typeof(Module), typeof(ModulePermission), typeof(OperateLog), typeof(PasswordLib), typeof(Permission), typeof(Role), typeof(RoleModulePermission), typeof(sysUserInfo), typeof(Topic), typeof(TopicDetail), typeof(UserRole)); // 后期单独处理某些表 //myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo)); //myContext.Db.CodeFirst.InitTables(typeof(Permission)); //myContext.Db.CodeFirst.InitTables(typeof(Advertisement)); Console.WriteLine("Database:WMBlog created success!"); Console.WriteLine(); if (Appsettings.app(new string[] { "AppSettings", "SeedDBDataEnabled" }).ObjToBool()) { Console.WriteLine("Seeding database..."); #region BlogArticle if (!await myContext.Db.Queryable <BlogArticle>().AnyAsync()) { var strJson = GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle")); myContext.GetEntityDB <BlogArticle>().InsertRange(JsonHelper.ParseFormByJson <List <BlogArticle> >(GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle")))); Console.WriteLine("Table:BlogArticle created success!"); } else { Console.WriteLine("Table:BlogArticle already exists..."); } #endregion #region Module if (!await myContext.Db.Queryable <Module>().AnyAsync()) { myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module")))); Console.WriteLine("Table:Module created success!"); } else { Console.WriteLine("Table:Module already exists..."); } #endregion #region Permission if (!await myContext.Db.Queryable <Permission>().AnyAsync()) { myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission")))); Console.WriteLine("Table:Permission created success!"); } else { Console.WriteLine("Table:Permission already exists..."); } #endregion #region Role if (!await myContext.Db.Queryable <Role>().AnyAsync()) { myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")))); Console.WriteLine("Table:Role created success!"); } else { Console.WriteLine("Table:Role already exists..."); } #endregion #region RoleModulePermission if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync()) { myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission")))); Console.WriteLine("Table:RoleModulePermission created success!"); } else { Console.WriteLine("Table:RoleModulePermission already exists..."); } #endregion #region Topic if (!await myContext.Db.Queryable <Topic>().AnyAsync()) { myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic")))); Console.WriteLine("Table:Topic created success!"); } else { Console.WriteLine("Table:Topic already exists..."); } #endregion #region TopicDetail if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync()) { myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail")))); Console.WriteLine("Table:TopicDetail created success!"); } else { Console.WriteLine("Table:TopicDetail already exists..."); } #endregion #region UserRole if (!await myContext.Db.Queryable <UserRole>().AnyAsync()) { myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")))); Console.WriteLine("Table:UserRole created success!"); } else { Console.WriteLine("Table:UserRole already exists..."); } #endregion #region sysUserInfo if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync()) { myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")))); Console.WriteLine("Table:sysUserInfo created success!"); } else { Console.WriteLine("Table:sysUserInfo already exists..."); } #endregion Console.WriteLine("Done seeding database."); } Console.WriteLine(); } catch (Exception ex) { throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message); } }
public static void EnsureSeedData(IServiceProvider serviceProvider) { /* * 本项目同时支持Mysql和Sqlserver,我一直使用的是Mysql,所以Mysql的迁移文件已经配置号,在Data文件夹下, * 直接执行update-database xxxx,那三步即可。如果你使用sqlserver,可以先从迁移开始,下边有步骤 * * 当然你也可以都删掉,自己重新做迁移。 * 迁移完成后,执行dotnet run /seed * 1、PM> add-migration InitialIdentityServerPersistedGrantDbMigrationMysql -c PersistedGrantDbContext -o Data/MigrationsMySql/IdentityServer/PersistedGrantDb * Build started... * Build succeeded. * To undo this action, use Remove-Migration. * 2、PM> update-database -c PersistedGrantDbContext * Build started... * Build succeeded. * Applying migration '20200509165052_InitialIdentityServerPersistedGrantDbMigrationMysql'. * Done. * 3、PM> add-migration InitialIdentityServerConfigurationDbMigrationMysql -c ConfigurationDbContext -o Data/MigrationsMySql/IdentityServer/ConfigurationDb * Build started... * Build succeeded. * To undo this action, use Remove-Migration. * 4、PM> update-database -c ConfigurationDbContext * Build started... * Build succeeded. * Applying migration '20200509165153_InitialIdentityServerConfigurationDbMigrationMysql'. * Done. * 5、PM> add-migration AppDbMigration -c ApplicationDbContext -o Data/MigrationsMySql * Build started... * Build succeeded. * To undo this action, use Remove-Migration. * 6、PM> update-database -c ApplicationDbContext * Build started... * Build succeeded. * Applying migration '20200509165505_AppDbMigration'. * Done. * */ Console.WriteLine("Seeding database..."); using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope()) { scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate(); { var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>(); context.Database.Migrate(); EnsureSeedData(context); } { var context = scope.ServiceProvider.GetService <ApplicationDbContext>(); context.Database.Migrate(); var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >(); var roleMgr = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >(); var BlogCore_Users = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))); var BlogCore_Roles = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))); var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))); foreach (var user in BlogCore_Users) { if (user == null || user.uLoginName == null) { continue; } var userItem = userMgr.FindByNameAsync(user.uLoginName).Result; var rid = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == user.uID)?.RoleId; var rName = BlogCore_Roles.Where(d => d.Id == rid).Select(d => d.Id).ToList(); var roleName = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name; if (userItem == null) { if (rid > 0 && rName.Count > 0) { userItem = new ApplicationUser { UserName = user.uLoginName, LoginName = user.uRealName, sex = user.sex, age = user.age, birth = user.birth, addr = user.addr, tdIsDelete = user.tdIsDelete, Email = user.uLoginName + "@email.com", EmailConfirmed = true, RealName = user.uRealName, }; //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result; // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了,可以先登录,然后修改密码 var result = userMgr.CreateAsync(userItem, "BlogIdp123$InitPwd").Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } var claims = new List <Claim> { new Claim(JwtClaimTypes.Name, user.uRealName), new Claim(JwtClaimTypes.Email, $"{user.uLoginName}@email.com"), new Claim("rolename", roleName), }; claims.AddRange(rName.Select(s => new Claim(JwtClaimTypes.Role, s.ToString()))); result = userMgr.AddClaimsAsync(userItem, claims).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表 } else { Console.WriteLine($"{user?.uLoginName} doesn't have a corresponding role."); } } else { Console.WriteLine($"{userItem?.UserName} already exists"); } } foreach (var role in BlogCore_Roles) { if (role == null || role.Name == null) { continue; } var roleItem = roleMgr.FindByNameAsync(role.Name).Result; if (roleItem != null) { role.Name = role.Name + Guid.NewGuid().ToString("N"); } roleItem = new ApplicationRole { CreateBy = role.CreateBy, Description = role.Description, IsDeleted = role.IsDeleted != null ? (bool)role.IsDeleted : true, CreateId = role.CreateId, CreateTime = role.CreateTime, Enabled = role.Enabled, Name = role.Name, OrderSort = role.OrderSort, }; var result = roleMgr.CreateAsync(roleItem).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine($"{roleItem?.Name} created");//AspNetUserClaims 表 } } } Console.WriteLine("Done seeding database."); Console.WriteLine(); }
public static async Task SeedAsync(MyContext myContext) { try { // myContext.Db.DbMaintenance.CreateDatabase(); myContext.CreateTableByEntity(false, typeof(RoleInfo), typeof(UserInfo), typeof(UserRole), typeof(ShopInfo) ); // myContext.Db.CodeFirst.InitTables(typeof(UserRole)); Console.WriteLine("dataBase:shop created success!"); Console.WriteLine(""); Console.WriteLine("seed dataBase..."); if (!await myContext.Db.Queryable <UserInfo>().AnyAsync()) { myContext.GetEntityDB <UserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <UserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserInfo")))); Console.WriteLine("Table:UserInfo created success!"); } else { Console.WriteLine("Table:UserInfo already exists..."); } if (!await myContext.Db.Queryable <RoleInfo>().AnyAsync()) { myContext.GetEntityDB <RoleInfo>().InsertRange(JsonHelper.ParseFormByJson <List <RoleInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleInfo")))); Console.WriteLine("Table:RoleInfo created success!"); } else { Console.WriteLine("Table:RoleInfo already exists..."); } if (!await myContext.Db.Queryable <UserRole>().AnyAsync()) { myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")))); Console.WriteLine("Table:UserRole created success!"); } else { Console.WriteLine("Table:UserRole already exists..."); } if (!await myContext.Db.Queryable <ShopInfo>().AnyAsync()) { myContext.GetEntityDB <ShopInfo>().InsertRange(JsonHelper.ParseFormByJson <List <ShopInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "ShopInfo")))); Console.WriteLine("Table:ShopInfo created success!"); } else { Console.WriteLine("Table:ShopInfo already exists..."); } Console.WriteLine("Done seeding database."); Console.WriteLine(); } catch (Exception ex) { throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message); } }
public static void EnsureSeedData(IServiceProvider serviceProvider) { //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data //4.dotnet run /seed Console.WriteLine("Seeding database..."); using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope()) { scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate(); { var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>(); context.Database.Migrate(); EnsureSeedData(context); } { var context = scope.ServiceProvider.GetService <ApplicationDbContext>(); context.Database.Migrate(); var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >(); var roleMgr = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >(); var BlogCore_Users = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))); var BlogCore_Roles = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))); var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))); foreach (var user in BlogCore_Users) { if (user == null || user.uLoginName == null) { continue; } var userItem = userMgr.FindByNameAsync(user.uLoginName).Result; var rid = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == user.uID)?.RoleId; var rName = BlogCore_Roles.Where(d => d.Id == rid).Select(d => d.Id).ToList(); if (userItem == null) { if (rid > 0 && rName.Count > 0) { userItem = new ApplicationUser { UserName = user.uLoginName, LoginName = user.uRealName, sex = user.sex, age = user.age, birth = user.birth, addr = user.addr, tdIsDelete = user.tdIsDelete }; //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result; // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了 var pwdInit = "BlogIdp123$InitPwd"; //if (userItem.UserName== "blogadmin") //{ // pwdInit = "#InitPwd"; //} var result = userMgr.CreateAsync(userItem, pwdInit).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } var claims = new List <Claim> { new Claim(JwtClaimTypes.Name, user.uRealName), new Claim(JwtClaimTypes.Email, $"{user.uLoginName}@email.com"), }; claims.AddRange(rName.Select(s => new Claim(JwtClaimTypes.Role, s.ToString()))); result = userMgr.AddClaimsAsync(userItem, claims).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表 } else { Console.WriteLine($"{user?.uLoginName} doesn't have a corresponding role."); } } else { Console.WriteLine($"{userItem?.UserName} already exists"); } } foreach (var role in BlogCore_Roles) { if (role == null || role.Name == null) { continue; } var roleItem = roleMgr.FindByNameAsync(role.Name).Result; if (roleItem != null) { role.Name = role.Name + Guid.NewGuid().ToString("N"); } roleItem = new ApplicationRole { CreateBy = role.CreateBy, Description = role.Description, IsDeleted = role.IsDeleted != null ? (bool)role.IsDeleted : true, CreateId = role.CreateId, CreateTime = role.CreateTime, Enabled = role.Enabled, Name = role.Name, OrderSort = role.OrderSort, }; var result = roleMgr.CreateAsync(roleItem).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } Console.WriteLine($"{roleItem?.Name} created");//AspNetUserClaims 表 } } } Console.WriteLine("Done seeding database."); Console.WriteLine(); }
/// <summary> /// 异步添加种子数据 /// </summary> /// <param name="myContext"></param> /// <returns></returns> public static async Task SeedAsync(MyContext myContext) { try { // 创建数据库 myContext.Db.DbMaintenance.CreateDatabase(); // 创建表 myContext.CreateTableByEntity(false, typeof(Module), typeof(Permission), typeof(Role), typeof(RoleModulePermission), typeof(SysAdmin), typeof(CCT), typeof(Clazz), typeof(Course), typeof(Exam), typeof(ExamDetail), typeof(ExamDetailScore), typeof(ExScore), typeof(Grade), typeof(Students), typeof(Teacher), typeof(UserRole)); Console.WriteLine("Database:WMBlog created success!"); Console.WriteLine(); Console.WriteLine("Seeding database..."); #region Module if (!await myContext.Db.Queryable <Module>().AnyAsync()) { myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module")))); Console.WriteLine("Table:Module created success!"); } else { Console.WriteLine("Table:Module already exists..."); } #endregion #region Permission if (!await myContext.Db.Queryable <Permission>().AnyAsync()) { myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission")))); Console.WriteLine("Table:Permission created success!"); } else { Console.WriteLine("Table:Permission already exists..."); } #endregion #region Role if (!await myContext.Db.Queryable <Role>().AnyAsync()) { myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")))); Console.WriteLine("Table:Role created success!"); } else { Console.WriteLine("Table:Role already exists..."); } #endregion #region RoleModulePermission if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync()) { myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission")))); Console.WriteLine("Table:RoleModulePermission created success!"); } else { Console.WriteLine("Table:RoleModulePermission already exists..."); } #endregion #region UserRole if (!await myContext.Db.Queryable <UserRole>().AnyAsync()) { myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")))); Console.WriteLine("Table:UserRole created success!"); } else { Console.WriteLine("Table:UserRole already exists..."); } #endregion #region SysAdmin if (!await myContext.Db.Queryable <SysAdmin>().AnyAsync()) { myContext.GetEntityDB <SysAdmin>().InsertRange(JsonHelper.ParseFormByJson <List <SysAdmin> >(GetNetData.Get(string.Format(GitJsonFileFormat, "SysAdmin")))); Console.WriteLine("Table:SysAdmin created success!"); } else { Console.WriteLine("Table:SysAdmin already exists..."); } #endregion Console.WriteLine("Done seeding database."); Console.WriteLine(); } catch (Exception ex) { throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message); } }
/// <summary> /// 异步添加种子数据 /// </summary> /// <param name="myContext"></param> /// <returns></returns> public static async Task SeedAsync(MyContext myContext) { try { // 注意!一定要先手动创建一个【空的数据库】 // 如果生成过了,第二次,就不用再执行一遍了,注释掉该方法即可 myContext.CreateTableByEntity(false, typeof(Advertisement), typeof(BlogArticle), typeof(Guestbook), typeof(Module), typeof(ModulePermission), typeof(OperateLog), typeof(PasswordLib), typeof(Permission), typeof(Role), typeof(RoleModulePermission), typeof(sysUserInfo), typeof(Topic), typeof(TopicDetail), typeof(UserRole)); // 后期单独处理某些表 //myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo)); //myContext.Db.CodeFirst.InitTables(typeof(Permission)); //myContext.Db.CodeFirst.InitTables(typeof(Advertisement)); #region BlogArticle if (!await myContext.Db.Queryable <BlogArticle>().AnyAsync()) { myContext.GetEntityDB <BlogArticle>().InsertRange(JsonHelper.ParseFormByJson <List <BlogArticle> >(GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle")))); } #endregion #region Module if (!await myContext.Db.Queryable <Module>().AnyAsync()) { myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module")))); } #endregion #region Permission if (!await myContext.Db.Queryable <Permission>().AnyAsync()) { myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission")))); } #endregion #region Role if (!await myContext.Db.Queryable <Role>().AnyAsync()) { myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")))); } #endregion #region RoleModulePermission if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync()) { myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission")))); } #endregion #region Topic if (!await myContext.Db.Queryable <Topic>().AnyAsync()) { myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic")))); } #endregion #region TopicDetail if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync()) { myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail")))); } #endregion #region UserRole if (!await myContext.Db.Queryable <UserRole>().AnyAsync()) { myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")))); } #endregion #region sysUserInfo if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync()) { myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")))); } #endregion } catch (Exception ex) { throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message); } }