You are on page 1of 3

Entity Framework Core :

Update database or migrations without


source code and Visual Studio
Author: tuanv2t@gmail.com

After developing then we will deploy application to production.

We might want to apply some migrations or update the production database to the last ?

=> There can be some way

#1: Using Visual studio

#2: Without Visual studio

Using Visual Studio


This is the most easy way to do, just replace the connection string in project with the connection
string to production and then run update-database

Without Visual studio


=> It's a little hard to do. In case we do not have permission to connect to the production
database

=> The idea is to generate script and send to our customers to run the script in productions =>
use :script-migration from Visual Studio source code

Script-Migration -from XXXX

If we want to generate script for the whole database , just run script-migration
If we want to generate script for a specific migration, provide the migration parameter -from or -
to , see more in official document

My real example project

The script is generated inside the visual studio.

If we not provide the -to then the Script-Migration will generate -from "migration" to the last

If we don't want to generate scipt, it's able to write some code to let EF automatically run
Migration

Apply migrations at runtime

myDbContext.Database.Migrate();

See example code:

public class Startup


{
...

public void ConfigureServices(IServiceCollection services)


{
services.AddDbContext<MyDbContext>(...);

...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)


{
UpdateDatabase(app);

...
}

private static void UpdateDatabase(IApplicationBuilder app)


{
using (var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
using (var context =
serviceScope.ServiceProvider.GetService<MyDbContext>())
{
context.Database.Migrate();
}
}
}
}

You might also like