如何使用脚本迁移在 ASP.NET 核心 2.2 中播种身份角色?

How do I seed Identity roles in ASP.NET Core 2.2 using Script-Migration?

我正在使用迁移来创建和播种我的数据库。由于我的数据库 运行 与我的 Web 应用程序位于不同的服务器上,因此我使用 Script-Migration 生成一个脚本,我可以 运行 在数据库服务器上。

根据官方EF Core Docs,我们可以使用HasData为我们的实体配置种子数据。有没有办法对身份角色或用户执行此操作?

对于HasData的播种数据,通常用于您自己定义的模型。

对于IdentityUserIdentityRole的种子数据,建议使用UserManager<IdentityUser>RoleManager<IdentityRole>。这是因为 HasData 可能无法正确设置许多属性,例如 PasswordHashConcurrencyStamp

检查这个问题How to seed the ASP.NET Identity model, and related seeding questions #736

您可以在 OnModelCreating() 方法中完成。请注意,必须预定义密钥以避免每次执行该方法时都播种新角色。下面的代码将创建一个新用户和一个新角色,并将角色关联到用户:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        
        base.OnModelCreating(modelBuilder);

        //Seeding a  'Administrator' role to AspNetRoles table
        modelBuilder.Entity<IdentityRole>().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<IdentityUser>();


        //Seeding the User to AspNetUsers table
        modelBuilder.Entity<IdentityUser>().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<IdentityUserRole<string>>().HasData(
            new IdentityUserRole<string>
            {
                RoleId = "2c5e174e-3b0e-446f-86af-483d56fd7210", 
                UserId = "8e445865-a24d-4543-a6c6-9443d048cdb9"
            }
        );
        

    }