Entity Framework Doing "Update-Database" within your code


Applications running in non-development environments often require database updates. After using the Add-Migration command to create your database patches there's the need to run the updates on other environments, and then the test environment as well.

Challenges commonly faced are:

  • no Visual Studio installed on production environments, and
  • no connections allowed to connection/customer environments in real life.

A workaround is the following code sequence which checks for updates to be performed, and executes them in order. Please ensure proper transactions & exception handling to ensure no data gets lost in case of errors.

void UpdateDatabase(MyDbConfiguration configuration) {
   DbMigrator dbMigrator = new DbMigrator( configuration);
   if ( dbMigrator.GetPendingMigrations().Any() )
      // there are pending migrations run the migration job

where MyDbConfiguration is your migration setup somewhere in your sources:

public class MyDbConfiguration : DbMigrationsConfiguration<ApplicationDbContext>