Entity framework 4.3 run migrations at application

2019-01-08 18:11发布

What is the best way to execute all required db migrations at application start with EF 4.3?

3条回答
在下西门庆
2楼-- · 2019-01-08 18:45

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楼-- · 2019-01-08 19:02

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));
    }
}
查看更多
Luminary・发光体
4楼-- · 2019-01-08 19:05

The best way should be using new MigrateDatabaseToLatestVersion initializer.

Database.SetInitializer<YourContext>(
    new MigrateDatabaseToLatestVersion<YourContext, YourMigrationsConfig>());
Database.Initialize(false);
查看更多
登录 后发表回答