[英]Run EF migrations on Startup in asp.net core 6 application
How can I run ef migrations on startup in asp.net 6 application.如何在 asp.net 6 应用程序中启动时运行 ef 迁移。
This is my Program.cs这是我的 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());
How can I execute MyContext.Database.Migrate() here?如何在这里执行 MyContext.Database.Migrate() ?
Try below:试试下面:
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();
Just add following lines in Program.cs只需在 Program.cs 中添加以下行
await using var scope = app.Services.CreateAsyncScope();
using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.