Starting EF migration when starting the application by code

Using the Entity Framework Migrations (Beta1), using the Update-Database command, works well during the development process.

But when the application is running somewhere on some client server, I really want my application to automatically update its database schema to the latest version when it was running.

Is it possible? There is little documentation.

+6
source share
2 answers

They do not provide a way to do this before RTM, after which they promise a command line application and the msdeploy provider. Source: http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx

Of course, this is not satisfied, the powershell command is stored in the package directory and is plain text, it just loads the assembly called EntityFramework.Migrations.Commands stored in the same directory.

Tracing this assembly, I came to 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 little experiment, I figured out a few more things

  • Performing an update in the static constructor for your context is bad, since it interrupts the powershell commands, it is much better to add code to launch the application in another way (Global.asax, WebActivator or Main method).
  • The above code only works when using AutomaticMigrations, you need to set MigrationsNamespace to load manually created migrations.
  • The configuration class that I created should already exist in your project (added when installing the nuget migration package), so create an instance instead.

This means that the code is simplified to

 DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration()); dbMigrator.Update(null); 
+11
source

Other options for this issue are adding

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

to your Global.asax Application_Start method.

+4
source

Source: https://habr.com/ru/post/903785/


All Articles