I'm not satisfied with author's own answer marked as accepted solution. It's very unclear to me what the actual "solution" is here. It is only mentioned that one should "use Startup". No mention of the exact thing that actually resolves the issue.
我正在运行一个具有最少启动 API 的 .NET 6 ASP.NET 应用程序,并遇到了同样的问题。dotnet ef migrations
会调用我的启动代码,导致整个应用程序尝试启动,然后失败(特别是我有一个在启动时直接运行的服务,它尝试使用我正在积极尝试为其创建迁移的数据库表)。
我通过放弃最小的 API 并创建一个来解决这个问题Program
类,带有“假”public static IHostBuilder CreateHostBuilder
method.
public class Program
{
// Have a Main that actually runs/starts your app with all the logic
public static async Task Main(string[] args)
{
// Here I do automatic migrations...
// ...
// Web app initialization logic
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app
.MapControllers()
.RequireAuthorization();
// etc.
await app.RunAsync();
}
// Have a CreateHostBuilder that simply returns a default builder.
public static IHostBuilder CreateHostBuilder(string[] args)
{
Console.WriteLine("Doing Entity Framework migrations stuff, not starting full application");
return Host.CreateDefaultBuilder();
}
}
EF 将寻找CreateHostBuilder
中的方法Program
。如果找到它,它不会调用Main
,并且基本上跳过 web 应用程序的整个初始化并返回一个非常空的主机构建器,足以让 EF 完成其工作。
这感觉有点像黑客,以后可能不起作用。
为 EF Core 7.0+ 用户提供更好的解决方案
如果您使用 EF Core 7.0 或更高版本,请参阅这个答案 https://stackoverflow.com/a/76127936/439094。现在,您可以在以下情况下返回空主机构建器:EF.IsDesignTime https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.ef.isdesigntime?view=efcore-7.0 is true
:
// Program.cs
if (EF.IsDesignTime) {
new HostBuilder().Build().Run();
return;
}
// Normal startup
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseAuthentication();
// ...