ari*_*its 10 ef-migrations entity-framework-core asp.net-core
我在过去几个月做了一些版本升级,现在我注意到当我使用"删除迁移"删除我恢复的迁移时,它首先运行我的应用程序.
(我注意到,因为我们在启动时更新数据库,所以我遇到了无法删除迁移的情况,因为每次我尝试删除迁移时 - 它会自动运行启动,将迁移应用到db,然后删除失败它,因为它在db中看到它.)
任何的想法?
Tse*_*eng 25
在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
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是ASP.NET Core 2.0/EF Core 2.0,则可以更改以更好地覆盖此类情况,以便命令行工具可以更好地工作.
它归结为一个静态BuildWebHost方法,它配置整个应用程序,但不运行它.
Run Code Online (Sandbox Code Playgroud)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();
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
现在只有在执行应用程序时才会运行迁移.运行命令行工具时,仅BuildWebHost会调用它并且不会应用任何迁移.
| 归档时间: |
|
| 查看次数: |
5843 次 |
| 最近记录: |