种子实体和用户,角色?

您如何为用户,角色和应用程序特定实体设定种子? 似乎IdentityModel以其自己的Context为目标?

internal sealed class Configuration : DbMigrationsConfiguration { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Project.Models.SchoolContext context) { // Seed the Entities // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" } // ); // } } 

 protected override void Seed(Project.Models.ApplicationDbContext context) { if (!context.Roles.Any(r => r.Name == "AppAdmin")) { var store = new RoleStore(context); var manager = new RoleManager(store); var role = new IdentityRole { Name = "AppAdmin" }; manager.Create(role); } if (!context.Users.Any(u => u.UserName == "founder")) { var store = new UserStore(context); var manager = new UserManager(store); var user = new ApplicationUser {UserName = "founder"}; manager.Create(user, "ChangeItAsap!"); manager.AddToRole(user.Id, "AppAdmin"); } } 

我没有从迁移中获取种子,而是使用上下文db初始化程序。 我的上下文源自IdentityDbContext,因此我使用此方法为用户和角色设定种子:

来自ctor的电话和初始化程序:

 public class ApplicationDbContext : IdentityDbContext { private readonly IHttpContextBaseWrapper _httpContextBaseWrapper; static ApplicationDbContext() { // Set the database intializer which is run once during application start // This seeds the database with admin user credentials and admin role Database.SetInitializer(new ApplicationDbInitializer()); } ... 

那我的种子代码:

 public class ApplicationDbInitializer : CreateDatabaseIfNotExists { protected override void Seed(ApplicationDbContext context) { InitializeIdentityForEF(context); base.Seed(context); } public static void InitializeIdentityForEF(ApplicationDbContext db) { if (!db.Users.Any()) { var roleStore = new RoleStore(db); var roleManager = new RoleManager(roleStore); var userStore = new UserStore(db); var userManager = new UserManager(userStore); // Add missing roles var role = roleManager.FindByName("Admin"); if (role == null) { role = new IdentityRole("Admin"); roleManager.Create(role); } // Create test users var user = userManager.FindByName("admin"); if (user == null) { var newUser = new ApplicationUser() { UserName = "admin", FirstName = "Admin", LastName = "User", Email = "xxx@xxx.net", PhoneNumber = "5551234567", MustChangePassword = false }; userManager.Create(newUser, "Password1"); userManager.SetLockoutEnabled(newUser.Id, false); userManager.AddToRole(newUser.Id, "Admin"); } ...