A question on my EF Core 2 Getting Started course on Pluralsight asks:
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
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!
4 thoughts on “Quick Tips for Migrating EF Core at Runtime on Azure”
You need to be careful running migrations on application startup for non trivial applications.
If you are in a multi-server environment each instance of the application will try to migrate the database which can lead to a nasty race condition.
See ajcvickers comment on this github issue https://github.com/aspnet/EntityFrameworkCore/issues/11819
THANK YOU! Such an important point. Multi-server or containers, too.
I realize it is somewhat subjective, but I was curious why you didn’t suggest database first and SSDT? I’ve seen some of your previous courses on Pluralsight where you used this approach and was curious on your thoughts regarding ease of use and best practices for today.
Your idea is brilliant