Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Entity Framework (code first) migrations in production

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.

like image 367
devdigital Avatar asked Jun 01 '12 10:06

devdigital


People also ask

How do I code my first migration to an existing database?

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.

Can we run SQL script using Code First migrations?

First you need to create a migration. Then in the generated migration file you can write your SQL.

How do I use code first in Entity Framework?

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…


2 Answers

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

like image 191
WDRust Avatar answered Oct 23 '22 11:10

WDRust


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.

like image 21
mackie Avatar answered Oct 23 '22 09:10

mackie