运行 asp.net 核心 6 应用程序中启动时的 EF 迁移
Run EF migrations on Startup in asp.net core 6 application
如何在 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()?
尝试以下:
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<MyContext>();
context.Database.Migrate();
}
只需在 Program.cs
中添加以下行
await using var scope = app.Services.CreateAsyncScope();
using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();
如何在 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()?
尝试以下:
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<MyContext>();
context.Database.Migrate();
}
只需在 Program.cs
中添加以下行await using var scope = app.Services.CreateAsyncScope();
using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();