Seeding Identity 2.0 database

前端 未结 5 1569
走了就别回头了
走了就别回头了 2021-02-06 01:00

I have an ASP.NET MVC 5 project (razor engine) which has Identity 2.0 with Individual User Accounts. I am using Visual Studio Professional 2013

I have not found any clea

5条回答
  •  温柔的废话
    2021-02-06 01:36

    I think I can solve the riddle as to WHY the Seed is never triggered: because the Seed is called only when the application is trying to connect to the database, and NOT when the application starts.

    I have created examples and I have used your code successfully with and without migrations. But since you want to use it with migrations enabled, below is the sample code.

    VERY IMPORTANT: To actually see the breakpoint inside Seed, run the application, press Login and use the credentials from the seed function to get access to the application. In case you get "Invalid username or password", watch out for the manager.PasswordValidator property in IdentityConfig.cs :: Create(IdentityFactoryOptions options, IOwinContext context).

    1. Create a new ASP.NET MVC 5 project in VS2013

    2. Update all packages using Update-Package command.

    3. Enable-Migrations

    4. In the Configuration.cs created by migrations add the following code:

      internal sealed class Configuration : DbMigrationsConfiguration
          {
              public Configuration()
              {
                  AutomaticMigrationsEnabled = false;
              }

      protected override void Seed(ApplicationDbContext context) { bool itWorks = WriteReferenceData(context); base.Seed(context); } private bool WriteReferenceData(ApplicationDbContext ctx) { DbContextTransaction transaction = null; bool succeeded = false; try { transaction = ctx.Database.BeginTransaction(); CreateRoles(ctx); CreateUsers(ctx); ctx.SaveChanges(); transaction.Commit(); succeeded = true; } catch (Exception ex) { if (transaction != null) { transaction.Rollback(); transaction.Dispose(); } succeeded = false; } return succeeded; } private void CreateRoles(ApplicationDbContext ctx) { // Out of the box // ctx.Roles.AddOrUpdate( // new IdentityRole { Name = "Administrator" }, // new IdentityRole { Name = "Guest" } // ); // Another approach var RoleManager = new RoleManager(new RoleStore(ctx)); var roleName = "Administrator"; //Create role if it does not exist if (!RoleManager.RoleExists(roleName)) { var roleresult = RoleManager.Create(new IdentityRole(roleName)); } } private void CreateUsers(ApplicationDbContext ctx) { // Out of the box approach // ctx.Users.AddOrUpdate( // new ApplicationUser { Email = "foo@xyz.com", UserName = "foo@xyz.com" } // ); // Another approach var UserManager = new UserManager(new UserStore(ctx)); var user = new ApplicationUser() { UserName = "foo@xyz.com", Email="foo@xyz.com"}; var password = "Wh@tever777"; var adminresult = UserManager.Create(user, password); //Add User Admin to Role Administrator if (adminresult.Succeeded) { var result = UserManager.AddToRole(user.Id, "Administrator"); } } }
    5. In Global.asax.cs :: Application_Start(), add the following line:

      Database.SetInitializer(new MigrateDatabaseToLatestVersion());

    6. Run!

    If you also need a sample of code with migrations disabled, let me know.

提交回复
热议问题