I did some version upgrade in last months and now I noticed that when I use \"remove-migration\" to delete migration that I reverted, it\'s first run my app.
(I noti
In ASP.NET Core 2.1 the methods changed slightly. The general method is similar to the 2.0, just the methods name and return types have been changed.
public static void Main(string[] args)
{
CreateWebHostBuilder(args)
.Build()
.Migrate();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return new WebHostBuilder()
...; // Do not call .Build() here
}
If you are on ASP.NET Core 2.0/EF Core 2.0 then there's been a change to better cover such cases, so that the command line tools can work better.
It's pretty well covered in this announcement.
It boils down to having a static BuildWebHost
method which configures the whole application, but doesn't run it.
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(); }
Also with EF 2.0 it's now recommended to move the migrations to the main method after BuildWebHost
has been called. For example
public static void Main(string[] args)
{
var host = BuildWebHost(args)
.Migrate();
host.Run();
}
Where Migrate
is an extension method:
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;
}
Now migrations only run, when your application is executed. When you run command line tools, only BuildWebHost
will be called and no migrations applied.