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

前端 未结 10 1544
离开以前
离开以前 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 11:00

    You can seed Users and Roles in OnModelCreating() method inside IdentityDbContext.cs file as shown below. Notice that the keys have to be predefined to avoid seeding new users and roles everytime this method is executed.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            //Seeding a  'Administrator' role to AspNetRoles table
            modelBuilder.Entity().HasData(new IdentityRole {Id = "2c5e174e-3b0e-446f-86af-483d56fd7210", Name = "Administrator", NormalizedName = "ADMINISTRATOR".ToUpper() });
    
    
            //a hasher to hash the password before seeding the user to the db
            var hasher = new PasswordHasher();
    
    
            //Seeding the User to AspNetUsers table
            modelBuilder.Entity().HasData(
                new IdentityUser
                {
                    Id = "8e445865-a24d-4543-a6c6-9443d048cdb9", // primary key
                    UserName = "myuser",
                    NormalizedUserName = "MYUSER",
                    PasswordHash = hasher.HashPassword(null, "Pa$$w0rd")
                }
            );
    
    
            //Seeding the relation between our user and role to AspNetUserRoles table
            modelBuilder.Entity>().HasData(
                new IdentityUserRole
                {
                    RoleId = "2c5e174e-3b0e-446f-86af-483d56fd7210", 
                    UserId = "8e445865-a24d-4543-a6c6-9443d048cdb9"
                }
            );
            
    
        }
    

提交回复
热议问题