Skip to content

Instantly share code, notes, and snippets.

@angularsen
Last active November 5, 2019 09:08
Show Gist options
  • Save angularsen/c65c3e523597014e88acbeb0767fae13 to your computer and use it in GitHub Desktop.
Save angularsen/c65c3e523597014e88acbeb0767fae13 to your computer and use it in GitHub Desktop.
CreateOrMigrateDatabase()
// Call me on startup, such as in Application_Start() of Global.asax.cs
private static void CreateOrMigrateDatabase()
{
// Disable automatic migrations as it prevents us from deploying DB changes without breaking the production web instance.
Database.SetInitializer<ApplicationDbContext>(null);
var migrator = new DbMigrator(new Configuration());
// Order by migration names to get oldest first, such as 201403221133523_AddSetting
List<string> pendingMigrations = migrator.GetPendingMigrations().OrderBy(x => x).ToList();
List<string> localMigrations = migrator.GetLocalMigrations().OrderBy(x => x).ToList();
List<string> databaseMigrations = migrator.GetDatabaseMigrations().OrderBy(x => x).ToList();
// Sanity check, avoid trying to migrate a DB that is newer or has different history than our local migrations
if (pendingMigrations.Any())
{
bool migrationsCompatibleWithDb = localMigrations.StartsWith(databaseMigrations);
if (!migrationsCompatibleWithDb)
{
var ex = new Exception("Unable to migrate database. Not compatible.");
ex.Data["localMigrations"] = string.Join("\n", localMigrations);
ex.Data["databaseMigrations"] = string.Join("\n", databaseMigrations);
ex.Data["pendingMigrations"] = string.Join("\n", pendingMigrations);
throw ex;
}
Trace.TraceInformation($"Migrating DB from {databaseMigrations.LastOrDefault() ?? "(empty)"} to {pendingMigrations.Last()}");
migrator.Update(pendingMigrations.Last());
}
using (var db = new ApplicationDbContext())
{
db.Database.CreateIfNotExists();
db.Database.Initialize(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment