Files

37 lines
1.0 KiB
C#

using Microsoft.EntityFrameworkCore;
namespace DongfangHydro.Dashboard.Api.Data;
public static class DatabaseInitializer
{
public static async Task InitializeAsync(WebApplication app)
{
var autoMigrate = app.Configuration.GetValue("Database:AutoMigrate", false);
var seed = app.Configuration.GetValue("Database:Seed", false);
if (!autoMigrate && !seed)
{
return;
}
await using var scope = app.Services.CreateAsyncScope();
var dbContext = scope.ServiceProvider.GetRequiredService<DashboardDbContext>();
if (autoMigrate)
{
if (dbContext.Database.IsRelational())
{
await dbContext.Database.MigrateAsync();
}
else
{
await dbContext.Database.EnsureCreatedAsync();
}
}
if (seed)
{
await scope.ServiceProvider.GetRequiredService<DashboardSeeder>().SeedAsync(CancellationToken.None);
}
}
}