Triggering EF migration at application startup by code

こ雲淡風輕ζ 提交于 2019-12-28 18:07:08

问题


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.


回答1:


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);        



回答2:


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.



来源:https://stackoverflow.com/questions/8508280/triggering-ef-migration-at-application-startup-by-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!