Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

entity framework 4.1 - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...