Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering EF migration at application startup by code

Using Entity Framework Migrations (Beta1), using Update-Database command is all good during development.

But when the application is running on some customer's server somewhere, I really want my application to automatically update it's database schema to the latest version when it's started.

Is this possible? Documentation is scarce.

like image 483
Kristoffer Lindvall Avatar asked Dec 14 '11 16:12

Kristoffer Lindvall


People also ask

How do I code my first migration to an existing database?

The following is the procedure to create a Code First model on the existing database. Step 1: Create a Model using Entity Data Model Wizard. Step 2: Select the “Code First from Database” option and click "Next". Step 3: Set up a connection with the database and click on "Next".


2 Answers

They aren't providing a way to do this until RTM, at which point they have promised a command line app and a msdeploy provider. Source: http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx

Of course not being satisfied with that, the powershell command is stored in the packages directory and is plain text, it appears to just load up an assembly called EntityFramework.Migrations.Commands stored in the same directory.

Tracing through that assembly I came up with the following

public class MyContext : DbContext
{
  static MyContext()
  {
    DbMigrationsConfiguration configuration = new DbMigrationsConfiguration() {
      MigrationsAssembly = typeof(MyContext).Assembly,
      ContextType = typeof(MyContext),
      AutomaticMigrationsEnabled = true,                
    };

    DbMigrator dbMigrator = new DbMigrator(configuration);          
    dbMigrator.Update(null);            
  }
}

UPDATE: after a bit of experimentation I figured out a few more things

  • Performing an update in the static constructor for your context is bad as it breaks the powershell commands, much better off adding the code to application startup another way (Global.asax, WebActivator or Main method)
  • The above code only works when using AutomaticMigrations, you need to set the MigrationsNamespace for it to pickup on manually created migrations
  • The configuration class I was creating should already exist in your project (added when you install the migration nuget package), so just instantiate that instead.

Which means the code is simplified to

DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration());
dbMigrator.Update(null);        
like image 194
Betty Avatar answered Oct 20 '22 19:10

Betty


Another options for this issue is to add

Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, NAMESPACE.TO.MIGRATIONS.Configuration>());

line to your Global.asax Application_Start method.

like image 26
Alex Titarenko Avatar answered Oct 20 '22 17:10

Alex Titarenko