Daily Archives: May 22, 2019

Quick Tips for Migrating EF Core at Runtime on Azure

A question on my EF Core 2 Getting Started course on Pluralsight asks:

Hi Julie
Thank you for your course. I have a question. Can you please advise what is the best practice to deploy code first migration to the production database (azure).? I mean i have created 
asp.net core mvc and ef.core application using the code first migration approach. after deployed to azure. If i change any schema in our code first approach how can i update schema in production database ( without loosing the data in production database)

My response with a few ideas I thought were worth sharing outside of the course discussion. (Note that this is just high level)

For simple solutions, one path I have used is to call database.migrate at startup. The VS publish workflow has an option you can check to apply migrations when the app is published. You can see this in the MS docs for deploying an aspnet core app to Azure:

Or you can do it programmaticly in the program.cs file which will perform any needed migrations. There’s an example of this in my April 2019 MSDN Magazine article . If you need something more robust, then you could instead generate scripts (perhaps Idempotent scripts) with EF Core migrations and then include them with your updates and use a tool that can apply those scripts. If you use Redgate tools, perhaps their SQL Change Automation tool. Another type of tool is a migrator tool like FlywayDB (flywaydb.org) or LiquidBase. I’ve used Flyway with containers. Here’s a very recent conference talk I did where I used it: bit.ly/30AhgAr