如何在 ASP.NET 6 应用程序启动时运行 ef 迁移。
这是我的Program.cs
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var serverVersion = new MySqlServerVersion(new Version(8, 0, 23));
builder.Services.AddDbContext<MyContext>(x => x.UseMySql(connectionString, serverVersion)
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging()
.EnableDetailedErrors());
如何在这里执行 MyContext.Database.Migrate() ?
尝试以下:
var app = builder.Build();
// omitted
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<MyContext>();
context.Database.Migrate();
}
// omitted
app.Run();
只需在 Program.cs 中添加以下行
await using var scope = app.Services.CreateAsyncScope();
await using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();