How to Seed Users and Roles with Code First Migration using Identity ASP.NET Core

前端 未结 10 1557
离开以前
离开以前 2020-12-04 10:12

I have created a new clean asp.net 5 project (rc1-final). Using Identity Authentication I just have the ApplicationDbContext.cs with the following code:

publ         


        
10条回答
  •  醉酒成梦
    2020-12-04 10:42

    If you have async issues, try the following code:

        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.
    
            string[] roles = new string[] { "Admin", "User" };
            foreach (string role in roles)
            {
                if (!context.Roles.Any(r => r.Name == role))
                {
                    context.Roles.Add(new IdentityRole(role));
                }
            }
    
            //create user UserName:Owner Role:Admin
            if (!context.Users.Any(u => u.UserName == "Owner"))
            {
                var userManager = new UserManager(new UserStore(context));
                var user = new ApplicationUser
                {
                    FirstName = "XXXX",
                    LastName = "XXXX",
                    Email = "xxxx@example.com",
                    UserName = "Owner",
                    PhoneNumber = "+111111111111",
                    EmailConfirmed = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    PasswordHash = userManager.PasswordHasher.HashPassword("secret"),
                    LockoutEnabled = true,
                };
                userManager.Create(user);
                userManager.AddToRole(user.Id, "Admin");
            }            
    
            context.SaveChanges();
        }
    

提交回复
热议问题