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 noticed that because we do update-database inside startup, so I got to situation where I can't remove migrations, since every time I tried remove migration - it automatically ran the startup which apply the migration to db, then it failed delete it, since it see it in db.)
any idea?
Remove a migrationTo remove the last migration, use this command. After removing the migration, you can make the additional model changes and add it again. Avoid removing any migrations which have already been applied to production databases.
You can rollback your migration by using rake db:rollback with different options. The syntax will be different according to your requirements. where n is number of migrations to rollback, counting from latest migration.
The Migrations feature enables you to change the data model and deploy your changes to production by updating the database schema without having to drop and re-create the database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With