asp.net 核心 2 中的种子数据库用户和角色 table

Seed database user and role table in asp.net core 2

我正在做一个 Asp.Net 核心 2.0 项目,我想播种 AspnetUserAspNetRolesAspNetUserRoles 表。我创建了一个 class 来播种数据库,如下所示:

public class SeedData
{

    public SeedData()
    {

    }

    public static async Task Seeding(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager, ApplicationDbContext context)
    {
        if (!context.Roles.Any())
        {

            context.Roles.AddRange(
                 new ApplicationRole
                 {
                     Id = "b562e963-6e7e-4f41-8229-4390b1257hg6",
                     Description = "This Is Admin User",
                     Name = "Admin",
                     NormalizedName = "ADMIN"

                 });
            context.SaveChanges();
        }


        if (!context.Users.Any())
        {
            ApplicationUser user = new ApplicationUser
            {
                FirstName = "MyName",
                LastName = "MyFamily",
                PhoneNumber = "9998885554",
                UserName = "saedbfd",
                Email = "myEmail@email.com",
                gender = 1
            };

            IdentityResult result = await userManager.CreateAsync(user, "123aA@");
            if (result.Succeeded)
            {
                ApplicationRole approle = await roleManager.FindByIdAsync("b562e963-6e7e-4f41-8229-4390b1257hg6");
                if (approle != null)
                {
                    await userManager.AddToRoleAsync(user, "Admin");    
                }
            }
        }

    }
}

以上代码是我的种子 class,它在 3 个表中插入数据:AspNetUsers、AspNetRolse 和 AspNetUserRoles

应用程序角色模型:

public class ApplicationRole : IdentityRole
{
    public string Description  { get; set; }
}

应用程序用户模型:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte gender { get; set; }
}

最后这是我的 Program.cs Class:

public class Program
{

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
                var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
                var context = services.GetRequiredService<ApplicationDbContext>();
                SeedData.Seeding(userManager,roleManager,context);//<---Do your seeding here
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

        public static IWebHost BuildWebHost(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .Build();

    }

然后我将此代码添加到 startup.cs 中的 configure 方法:

     using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
        }

一切都很好,在 运行 应用程序数据库自动创建并创建所有表并在 AspNetUsersAspNetRoles 中插入重新编码之后,但出现了问题。问题是未在种子 class 中的 AspNetUserRoles 中插入任何行。 我的代码有什么问题?

我可以通过更改 SeedData class

来解决我的问题
public class SeedData
{

    public SeedData()
    {

    }

    public static async Task Seeding(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager, ApplicationDbContext context)
    {
        if (!context.Roles.Any())
        {
            context.Roles.AddRange(
                 new ApplicationRole
                 {
                     Id = "b562e963-6e7e-4f41-8229-4390b1257hg6",
                     Description = "This Is AdminUser",
                     Name = "Admin",
                     NormalizedName = "ADMIN"

                 });

            context.SaveChanges();
        }


        if (!context.Users.Any())
        {
            ApplicationUser user = new ApplicationUser
            {
                FirstName = "MyFirstName",
                LastName = "MyLastName",
                PhoneNumber = "9998885554",
                UserName = "saedbfd",
                NormalizedUserName = "SAEDBFD",
                Email = "MyEmail@Email.com",
                NormalizedEmail="MYEMAIL@EMAIL.COM",
                gender = 1,
                PasswordHash = "AQAAAAEAACcQAAAAEH9MTIiZG90QJrMLt62Zd4Z8O5o5MaeQYYc/53e2GbawhGcx2JNUSmF0pCz9H1AnoA==",
                LockoutEnabled = true,
                SecurityStamp = "aea97aa5-8fb4-40f2-ba33-1cb3fcd54720"
            };

            context.Users.Add(user);
            context.SaveChanges();


            IdentityUserRole<string> ur = new IdentityUserRole<string>();
            ur.RoleId = "b562e963-6e7e-4f41-8229-4390b1257hg6";
            ur.UserId = user.Id;

            context.UserRoles.Add(ur);
            context.SaveChanges();

    }
}

所有数据都正确插入数据库,一切正常。