ASP.NET Core 2.1 更新
在 ASP.NET Core 2.1 中,方法略有改变。通用方法与2.0类似,只是方法名和返回类型有所改变。
public static void Main(string[] args)
{
CreateWebHostBuilder(args)
.Build()
.Migrate();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return new WebHostBuilder()
...; // Do not call .Build() here
}
ASP.NET Core 2.0
如果您使用的是 ASP.NET Core 2.0/EF Core 2.0,则为了更好地覆盖此类情况,我们进行了更改,以便命令行工具可以更好地工作。
this announcement 很好地涵盖了它。
归结为有一个静态的BuildWebHost 方法来配置整个应用程序,但不运行它。
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
host.Run();
}
// Tools will use this to get application services
public static IWebHost BuildWebHost(string[] args) =>
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
此外,对于 EF 2.0,现在建议在调用 BuildWebHost 之后将迁移移至 main 方法。例如
public static void Main(string[] args)
{
var host = BuildWebHost(args)
.Migrate();
host.Run();
}
Migrate 是一个扩展方法:
public static IWebHost Migrate(this IWebHost webhost)
{
using (var scope = webhost.Services.GetService<IServiceScopeFactory>().CreateScope())
{
using (var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>())
{
dbContext.Database.Migrate();
}
}
return webhost;
}
现在迁移仅在您的应用程序执行时运行。当您运行命令行工具时,只会调用 BuildWebHost 并且不会应用迁移。