Entity framework 4.3 launches migration at application startup

What is the best way to perform all the necessary db migrations when starting the application with EF 4.3?

+31
migration entity-framework ef-migrations
Feb 14 2018-12-12T00:
source share
3 answers

The best way is to use the new MigrateDatabaseToLatestVersion initializer.

 Database.SetInitializer<YourContext>( new MigrateDatabaseToLatestVersion<YourContext, YourMigrationsConfig>()); Database.Initialize(false); 
+50
Feb 14 '12 at 21:30
source share

An excellent description of the EF 4.3 configuration parameters can be found on EF 4.3 Configuring the configuration file on the ADO.NET team blog. The last section describes the database initializers, including the new initializer for the first code <1>.

Although the Entity Framework, like many other .NET 4.x features, supports a configuration convention, this is one example where it would be very useful to install the MigrateDatabaseToLatestVersion database MigrateDatabaseToLatestVersion through the application configuration file, rather than explicitly copy it to your application.

+6
Feb 16 '12 at 17:40
source share

I needed to do this explicitly because I am using uber-context for migration, a superset of other migrations. Key bit:

 var dbMigrator = new System.Data.Entity.Migrations.DbMigrator( new Lcmp.EF.Migrations.Migrations.Configuration()); dbMigrator.Update(); 

When sprinkling Elmah magazine, I use this, called from Application_Start (). Pieces of it are stolen from the ideas of others. I'm not sure if a blocked part with thread protection is needed.

 public static int IsMigrating = 0; private static void UpdateDatabase() { try { if (0 == System.Threading.Interlocked.Exchange(ref IsMigrating, 1)) { try { // Automatically migrate database to catch up. Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Checking db for pending migrations."))); var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(new Lcmp.EF.Migrations.Migrations.Configuration()); var pendingMigrations = string.Join(", ", dbMigrator.GetPendingMigrations().ToArray()); Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("The database needs these code updates: " + pendingMigrations))); dbMigrator.Update(); Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(new Exception("Done upgrading database."))); } finally { System.Threading.Interlocked.Exchange(ref IsMigrating, 0); } } } catch (System.Data.Entity.Migrations.Infrastructure.AutomaticDataLossException ex) { Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(ex)); } catch (Exception ex) { Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(ex)); } } 
+4
May 24 '12 at 9:50 a.m.
source share



All Articles