Running & Scripting Migrations from Code
Code First Migrations is included as part of Entity Framework starting with the EF 4.3 release.
Migrations are normally created and run from the Package Manager Console in Visual Studio. These commands are just thin wrappers over public APIs that you can call directly from your own code. In this post you’ll see how to kick-off the migrations process from code. You’ll also see how to get a SQL script that represents the changes from a set of migrations.
I’m going to assume you have a working knowledge of Code First Migrations… if you don’t, take a minute to read the Code-Based Migrations Walkthrough.
Running Migrations from Code
Running migrations is actually very simple. You need to instantiate an instance on the Configuration class that was added to your project when you enabled migrations, this is then used to construct a DbMigrator. Calling the Update method will then update the target database to the latest migration. There is also an overload that allows you to specify a target migration to upgrade/downgrade to.
var configuration = new Configuration(); var migrator = new DbMigrator(configuration); migrator.Update();
The above code will update that database that your context targets. You can override the database that will be migrated by setting the TargetDatabase property on the configuration.
var configuration = new Configuration(); configuration.TargetDatabase = new DbConnectionInfo( "Server=MyServer;Database=MyDatabase;Trusted_Connection=True;", "System.Data.SqlClient"); var migrator = new DbMigrator(configuration); migrator.Update();
Scripting Migrations from Code
Scripting migrations is very simiar, except you wrap the DbMigrator in a MigratorScriptingDecorator. You can then use the ScriptUpdate method to get the resulting SQL script as a string. The source and target migrations allow you to get a script between any two given migrations. If you supply null an empty database is used for the source migration and the latest migration is used for the target.
var configuration = new Configuration(); var migrator = new DbMigrator(configuration); var scriptor = new MigratorScriptingDecorator(migrator); string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
Our team has been careful to ensure that all the operations available as Power Shell commands can be easily performed from your code. This post showed how to use code to perform the operations available via the Update-Database command.