1. 程式人生 > >通過webhost擴展方式初始化EFCore數據庫

通過webhost擴展方式初始化EFCore數據庫

ans min urn aos ble ica cor container luna

通過webhost擴展方式初始化EFCore數據庫

EFCore數據庫初始化

1.定義WebHostMigrationExtensions類

 public static class WebHostMigrationExtensions
    {
        public static IWebHost MigrationDbContext<TContext>(this IWebHost host,
            Action<TContext, IServiceProvider> seeder) where TContext : DbContext
        {
            using
(var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var logger = services.GetRequiredService<ILogger<TContext>>(); var context = services.GetService<TContext>(); try { context.Database.Migrate(); seeder(context, services); logger.LogInformation($"執行DbContext{typeof
(TContext).Name}
seed執行成功!"
); } catch (Exception ex) { logger.LogError(ex, $"執行DbContext{typeof(TContext).Name} seed執行失敗!"); } } return host; } }
public class ApplicationContextSeed
{ private UserManager<User> _userManager; public async Task SeedAsync(ApplicationDbContext context,IServiceProvider service) { if (!context.Users.Any()) { _userManager = service.GetRequiredService<UserManager<User>>(); var defaultUser = new User { UserName = "[email protected]", Email = "[email protected]", NormalizedEmail= "[email protected]", NormalizedUserName = "admin" }; var result = await _userManager.CreateAsync(defaultUser, "pwd123456"); if (!result.Succeeded) { throw new Exception("初始化數據庫失敗"); } } } }

2.在buildWebHost中調用

public static void Main(string[] args)
        {
            BuildWebHost(args)
            .MigrationDbContext<ApplicationDbContext>((context, services) =>
                {
                    new ApplicationDbContextSeed().SeedAsync(context, services).Wait();
                })
                .Run();
        }

通過webhost擴展方式初始化EFCore數據庫