SeedData:

    1. public static class SeedData
    2. {
    3. /// <summary>
    4. /// 用户种子数据
    5. /// </summary>
    6. /// <param name="builder"></param>
    7. /// <returns></returns>
    8. public static IApplicationBuilder UseDataInitializer(this IApplicationBuilder builder)
    9. {
    10. using (var scope = builder.ApplicationServices.CreateScope())
    11. {
    12. var dbContext = scope.ServiceProvider.GetService<AppDbContext>();
    13. var userManager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
    14. Console.WriteLine("开始执行迁移数据库……");
    15. dbContext.Database.Migrate();
    16. Console.WriteLine("数据库迁移完成……");
    17. #region 初始化学生数据
    18. if (!dbContext.Students.Any())
    19. {
    20. Console.WriteLine("开始创建种子数据中……");
    21. dbContext.Students.Add(new Student
    22. {
    23. Id = 1,
    24. Name = "梁桐铭",
    25. ClassName = ClassNameEnum.FirstGrade,
    26. Email = "ltm@ddxc.org"
    27. });
    28. dbContext.Students.Add(new Student
    29. {
    30. Id = 2,
    31. Name = "角落的白板报",
    32. ClassName = ClassNameEnum.GradeThree,
    33. Email = "werltm@qq.com"
    34. });
    35. }
    36. #endregion
    37. #region 初始化用户
    38. var adminUser = dbContext.Users.FirstOrDefault(u => u.UserName == "ltm@ddxc.org");
    39. if (adminUser == null)
    40. {
    41. var user = new ApplicationUser
    42. {
    43. UserName = "ltm@ddxc.org",
    44. Email = "ltm@ddxc.org",
    45. EmailConfirmed = true,
    46. City = "成都"
    47. };
    48. var identityResult = userManager.CreateAsync(user, "bb123456").GetAwaiter().GetResult();
    49. var role = dbContext.Roles.Add(new IdentityRole
    50. {
    51. Name = "Admin",
    52. NormalizedName = "ADMIN"
    53. });
    54. dbContext.SaveChanges();
    55. dbContext.UserRoles.Add(new IdentityUserRole<string>
    56. {
    57. RoleId = role.Entity.Id,
    58. UserId = user.Id
    59. });
    60. var userClaims = new List<IdentityUserClaim<string>>
    61. {
    62. new IdentityUserClaim<string>
    63. {
    64. UserId = user.Id, ClaimType = "Create Role", ClaimValue = "Create Role"
    65. },
    66. new IdentityUserClaim<string>
    67. {
    68. UserId = user.Id, ClaimType = "Edit Role", ClaimValue = "Edit Role"
    69. },
    70. new IdentityUserClaim<string>
    71. {
    72. UserId = user.Id, ClaimType = "Delete Role", ClaimValue = "Delete Role"
    73. },
    74. new IdentityUserClaim<string>
    75. {
    76. UserId = user.Id, ClaimType = "Edit Student", ClaimValue = "Edit Student"
    77. }
    78. };
    79. dbContext.UserClaims.AddRange(userClaims);
    80. dbContext.SaveChanges();
    81. #endregion
    82. }
    83. else
    84. {
    85. Console.WriteLine("无需创建种子数据……");
    86. }
    87. }
    88. return builder;
    89. }
    90. }

    写好 SeedData 后,记得在 Startup 中进行调用:
    image.png
    并屏蔽 modelBuilder.Seed 的使用:
    image.png