Entity Framework Entity-framework Code First Migrations Doing "Update-Database" within your code

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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
      dbMigrator.Update(); 
   }
}

where MyDbConfiguration is your migration setup somewhere in your sources:

public class MyDbConfiguration : DbMigrationsConfiguration<ApplicationDbContext>


Got any Entity Framework Question?