Entity Framework Core Data Migration through KUDU

This is a cross-posting of Entity Framework 7 Data Migration through KUDU at Kloud.

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 Core (EF Core) uses DNX for it.

Applying Database Migration with EF Core

In EF Core RC1, updating database change can be done by running the following command:

https://gist.github.com/justinyoo/26c5ba404159cd57850b18c1b7fd5b52

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

https://gist.github.com/justinyoo/b7329197a7f60fd0cc88eea2f9bfbe80

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 RC1 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:

https://gist.github.com/justinyoo/19edb2eb788c3c5ccc31f457ddd42f67

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.

https://gist.github.com/justinyoo/a2d36c1aa6ae678e9c3e18d03b838828

NOTE: The dir property is where the actual command is run, which is the relative path to D:\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.