如何在 .net6 中使用默认值初始化数据库

How do I initialize database with default values in .net6

直到 .net5 我一直在 startup.cs 文件中使用以下内容播种数据:

SeedData.Seed(_userManager, _roleManager);

然后在一个单独的文件SeedData.cs中,如下代码:

public static class SeedData
{
    public static void Seed(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        SeedRoles(roleManager);
        SeedUsers(userManager);
    }

    private static void SeedUsers(UserManager<IdentityUser> userManager)
    {
        if(userManager.FindByNameAsync("admin@localhost.com").Result == null)
        {
            var user = new IdentityUser
            {
                UserName = "admin@localhost.com",
                Email = "admin@localhost.com"
            };

            var result = userManager.CreateAsync(user, "P@ssword1").Result;
            if(result.Succeeded)
            {
                userManager.AddToRoleAsync(user, "Administrator").Wait();
            }
        }
    }
    private static void SeedRoles(RoleManager<IdentityRole> roleManager)
    {
        if(!roleManager.RoleExistsAsync("Administrator").Result)
        {
            var role = new IdentityRole
            {
                Name = "Administrator",
            };
            var result = roleManager.CreateAsync(role).Result;
        }

        if(!roleManager.RoleExistsAsync("Employee").Result)
        {
            var role = new IdentityRole
            {
                Name = "Employee",
            };
            var result = roleManager.CreateAsync(role).Result;
        }
    }
}

现在,我如何对 .net6 做同样的事情,因为它只有 program.cs 个文件?

这是我个人的做法:

我对 IApplicationBuilder 进行了扩展:

public static class ApplicationBuilderExtensions
    {
        public static async Task<IApplicationBuilder> PrepareDatabase(this IApplicationBuilder app)
        {
            using var scopedServices = app.ApplicationServices.CreateScope();

        var serviceProvider = scopedServices.ServiceProvider;
        var data = serviceProvider.GetRequiredService<NeonatologyDbContext>();

        data.Database.Migrate();

        await SeedAdministratorAsync(serviceProvider);
        await SeedDoctorAsync(data, serviceProvider);


        return app;
    }

这是种子:

 private static async Task SeedDoctorAsync(NeonatologyDbContext data, IServiceProvider serviceProvider)
        {
            if (data.Doctors.Any())
            {
                return;
            }

            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = serviceProvider.GetRequiredService<RoleManager<ApplicationRole>>();

            var identityRole = new ApplicationRole()
            {
                Name = DoctorRoleName
            };

            await roleManager.CreateAsync(identityRole);

            var city = await data.Cities.Where(x => x.Name == "Плевен").FirstOrDefaultAsync();
            var doctor = new ApplicationUser()
            {
                Email = DoctorEmail,
                UserName = DoctorEmail,
                EmailConfirmed = true,
                Doctor = new Doctor
                {
                    FirstName = DoctorFirstName,
                    LastName = DoctorLastName,
                    PhoneNumber = DoctorPhone,
                    Address = Address,
                    Age = DoctorAge,
                    Biography = Biography,
                    CityId = city.Id,
                    City = city,
                    YearsOfExperience = YearsOfExperience,
                    Email = DoctorEmail
                }
            };

            await userManager.CreateAsync(doctor, DoctorPassword);
            await userManager.AddToRoleAsync(doctor, identityRole.Name);

            doctor.Doctor.UserId = doctor.Id;

            doctor.Doctor.Image = new Image()
            {
                RemoteImageUrl = "SomeURL"
            };

            await data.SaveChangesAsync();
        }

private static async Task SeedAdministratorAsync(IServiceProvider serviceProvider)
        {
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = serviceProvider.GetRequiredService<RoleManager<ApplicationRole>>();

            if (await roleManager.RoleExistsAsync(AdministratorRoleName))
            {
                return;
            }

            var identityRole = new ApplicationRole()
            {
                Name = AdministratorRoleName
            };

            await roleManager.CreateAsync(identityRole);

            const string adminEmail = AdministratorEmail;
            const string adminPassword = AdministratorPassword;

            var adminUser = new ApplicationUser()
            {
                Email = adminEmail,
                UserName = adminEmail,
                EmailConfirmed = true
            };

            if (await userManager.IsInRoleAsync(adminUser, identityRole.Name))
            {
                return;
            }

            await userManager.CreateAsync(adminUser, adminPassword);
            await userManager.AddToRoleAsync(adminUser, identityRole.Name);
        }

在 Program.cs 我有:

app.PrepareDatabase()
                .GetAwaiter()
                .GetResult();

以下代码片段适用于我,并在应用程序初始化时播种数据。