I am new to migrations and I can't find out what to do to get my changes onto the LiveDB.
So on dev when I add to my model I do
PM> add-migration <name>
PM> update-database
But what do I do on live? I was HOPING that I could just publish\deploy to live and the migration would run and update the schema, but I guess not :)
The Live SQL server is off in its own world I have no access to it from my dev box to just change the connectionstring and doing an update-database again.
What do you guys do, where's the docs?
Thanks, Steve
Updated with sample for 3.0
The Core 3.0 approach is similar to 2.x, but now the generic host is used.
You will need to add using Microsoft.Extensions.DependencyInjection;
for the CreateScope()
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var db = scope.ServiceProvider.GetService<ShortenerContext>();
db.Database.Migrate();
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Updated with better way for Core 2.0+
Migrations should be run in Program.cs due to tooling like the EF Core CLI tools running the Startup functions in normal execution.
Here is an example:
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var db = scope.ServiceProvider.GetService<ShortenerContext>();
db.Database.Migrate();
}
host.Run();
}
public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
One way to run migrations in 1.x is to just add something like this in app startup:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
ShortenerContext db)
{
db.Database.Migrate();
//Rest omitted
}
This will execute all pending migrations against the database on startup.
script-migration -From "last_migration_name" -To "current_migration_name"
or script-migration -idempotent
In you Start-up method add this code
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<AppDBContext>();
context.Database.Migrate();
}
This will execute and update all migrations on production
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