What is the best way to execute all required db migrations at application start with EF 4.3?
问题:
回答1:
The best way should be using new MigrateDatabaseToLatestVersion
initializer.
Database.SetInitializer<YourContext>(
new MigrateDatabaseToLatestVersion<YourContext, YourMigrationsConfig>());
Database.Initialize(false);
回答2:
A great description of the EF 4.3 configuration options can be found at EF 4.3 Configuration File Settings on the ADO.NET team blog. The very last section describes Database Initializers, including the new Code First MigrateDatabaseToLatestVersion
initializer.
Although Entity Framework—like so many other features of .NET 4.x—favors convention over configuration, this is one case where it might be very useful to set the MigrateDatabaseToLatestVersion
database initializer through your application's config file rather than explicitly code it into your application.
回答3:
I needed to do it explicitly, because I use an uber-context for migration, a superset of the other migrations. The key bit is:
var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(
new Lcmp.EF.Migrations.Migrations.Configuration());
dbMigrator.Update();
With a sprinkling of Elmah logging, I actually use this, called from Application_Start(). Pieces of it are stolen from others' ideas. I'm not positive that the thread-safety Interlocked part is necessary.
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));
}
}