How to seed an Admin user in EF Core 2.1.0?

后端 未结 6 1408
感情败类
感情败类 2020-11-29 02:40

I have an ASP.NET Core 2.1.0 application using EF Core 2.1.0.

How do I go about seeding the database with Admin user and give him/her an Admin role? I cannot find an

6条回答
  •  再見小時候
    2020-11-29 03:22

    The below worked for me without any other configuration, check the comments. The IDs have to be predefined to avoid seeding a new user with an new role named Administrator everytime OnModelCreating() method is executed. I am using AspNetCore 3.1.

    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"
                }
            );
            
    
        }
    

提交回复
热议问题