Triggering EF migration at application startup by code

前端 未结 2 1307
野性不改
野性不改 2020-12-10 17:32

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

But when the application is running on some customer\'s serv

相关标签:
2条回答
  • 2020-12-10 18:16

    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.

    0 讨论(0)
  • 2020-12-10 18:25

    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);        
    
    0 讨论(0)
提交回复
热议问题