From DevOps perspective, everything needs to be automated in regards to application setup and deployment. There’s no exception for database migration. If database schema change occurs, it should be automatically applied before/after the application deployment. Unlike Entity Framework 6.x using PowerShell cmdlets for database migration, Entity Framework 7 (EF7) uses DNX for it.

Applying Database Migration with EF7

In EF7, updating database change can be done by running the following command:

If your DbContext is located in another project and your web application has a reference to it, then you can run the following command:

By running the command above within your build/deployment pipeline, your database change is easily applied to the existing database. Connectionstrings are defined in appsettings.json in your ASP.NET Core application.

Visit https://docs.efproject.net for more details.

In most cases, there’s no issue to access to Azure SQL Database from your build/deployment server, as long as Azure SQL Database has a proper firewall setup. But what if your enterprise firewall doesn’t allow to connect to Azure SQL Database, like blocking the TCP port of 1433? Then we can’t run this command from our build/deployment server.

REST API in KUDU

KUDU is basically a backend service engine for deployment tied to your Azure Website. If you are running any Azure App Service, your KUDU can be accessible via https://your-azure-website.scm.azurewebsites.net. It provides REST API for website maintenance and one of its endpoint is command. Therefore, we can write a script, say db-migration.cmd, deploy it at the same time when the application is deployed, and run it through this REST API. The db-migration.cmd might look like:

So, the application is ready for database migration. Let’s write a PowerShell script to run the command. Make sure that we are using Azure Service Management (ASM) cmdlets.

NOTE: You should login to ASM with appropriate subscription first.

NOTE: The dir property is where the actual command is run, which is the relative path to %HOME% in Azure App Service.

Running the PS script above will bring you to database migration completed within KUDU. Make sure that the $result object has an exit code of 0 by examining $result.ExitCode. If the exit code is other than 0, database migration has come to fail.

So far, we have briefly looked at KUDU for Azure SQL Database migration. KUDU actually has many useful functions for monitoring, so it would be worth taking a look.

Category:
Application Development and Integration, Azure Platform, PowerShell
Tags:
, , , ,

Comments are closed.