MVC 5 Seed Users and Roles

前端 未结 7 1881
有刺的猬
有刺的猬 2020-11-28 01:56

I have been playing about with the new MVC 5, I have a few models, controller and views setup using code first migrations.

My question is how do I seed users and ro

7条回答
  •  自闭症患者
    2020-11-28 02:27

    protected override void Seed(ApplicationDbContext context)
    {
      SeedAsync(context).GetAwaiter().GetResult();
    }
    
    private async Task SeedAsync(ApplicationDbContext context)
    {
      var userManager = new ApplicationUserManager(new UserStore(context));
      var roleManager = new ApplicationRoleManager(new RoleStore(context));
    
      if (!roleManager.Roles.Any())
      {
        await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AdminRoleName });
        await roleManager.CreateAsync(new ApplicationRole { Name = ApplicationRole.AffiliateRoleName });
      }
    
      if (!userManager.Users.Any(u => u.UserName == "shimmy"))
      {
        var user = new ApplicationUser
        {
          UserName = "shimmy",
          Email = "shimmy@gmail.com",
          EmailConfirmed = true,
          PhoneNumber = "0123456789",
          PhoneNumberConfirmed = true
        };
    
        await userManager.CreateAsync(user, "****");
        await userManager.AddToRoleAsync(user.Id, ApplicationRole.AdminRoleName);
      }
    }
    

提交回复
热议问题