How to enable Code First Entity Framework Migrations for Windows Azure when publishing from source control?
-
21-12-2019 - |
Question
I have a project that I am publishing to Azure automatically through source control. I have configured azure to have a proper connection string for the entity framework context. I need to automatically run the migrations against azure database associated with the website.
I know there is an option in the publish dialog, but I need to manually add whatever magic goes into the web.config to tell azure to apply the migrations. What is required to have azure run migrations from source control and if this is not possible is there another way?
I am using EF 6.
Solution
You need is to configure your context to Migrate on run. You need to do this only once per running process so a static constructor on the context is a pretty decent place to put it
static MyContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Data.Migrations.Configuration>());
}
Also make sure a connection string is configured in Azure.
If you are using automatic migrations (which is a bad idea in a deployed site) then you will also need those enabled
OTHER TIPS
To run such migration scripts I'd recommend using Azure WebJobs: http://www.hanselman.com/blog/IntroducingWindowsAzureWebJobs.aspx
Azure WebJobs, is a scheduler for running scripts like .bat, .exe, etc. it basically works like cron on UNIX machines but offers intuitive and easy to use UI. So for @Romoku case, he could create console app. That uses EF 6.0 and all that .Net offers to schedule his migrations and track logs of the opearations. It works on the same machine and environment that website is running on.