I'm just looking into using EF migrations for our project, and in particular for performing schema changes in production between releases.
I have seen mentioned that there is an API to perform these migrations at run-time using the DbMigration
class, but I can't find any specific examples.
Ideally, I would want one DbMigration
file for every database change, and for those changes to be applied automatically on application start up from the current version up to the latest version.
Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.
First you need to create a migration. Then in the generated migration file you can write your SQL.
Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
There is a Database Initializer you can use to achieve the migration to latest version on startup (or better, the dbinitializer will kick in on first db access), the MigrateDatabaseToLatestVersion
, you use it like that:
Database.SetInitializer<ObjectContext>( new MigrateDatabaseToLatestVersion<ObjectContext, Configuration>());
Regarding having one file per migration, if you enable automatic migrations you will find them in the Migrations
folder (by default) in the root of your project.
Relevant info, with examples, here: http://weblogs.asp.net/fredriknormen/archive/2012/02/15/using-entity-framework-4-3-database-migration-for-any-project.aspx
This works too:
var configuration = new MyDbContextConfiguration(); configuration.TargetDatabase = new DbConnectionInfo( database.ConnectionString, database.ProviderName); var migrator = new DbMigrator(configuration); migrator.Update();
You can also call:
migrator.GetPendingMigrations();
to get a list of the migrations it needs to apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With