Last active
December 17, 2020 10:38
-
-
Save Warrenn/7da4ca4e2601667f10b651fdcddf4cce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void InitializeDatabase(YourDbContext context) | |
{ | |
if (!context.Database.Exists() || !context.Database.CompatibleWithModel(false)) | |
{ | |
var configuration = new DbMigrationsConfiguration(); | |
var migrator = new DbMigrator(configuration); | |
migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient"); | |
var migrations = migrator.GetPendingMigrations(); | |
if (migrations.Any()) | |
{ | |
var scriptor = new MigratorScriptingDecorator(migrator); | |
var script = scriptor.ScriptUpdate(null, migrations.Last()); | |
if (!string.IsNullOrEmpty(script)) | |
{ | |
context.Database.ExecuteSqlCommand(script); | |
} | |
} | |
} | |
} | |
public void InitializeDatabase(DbContext context) | |
{ | |
if (!context.Database.Exists() || !context.Database.CompatibleWithModel(false)) | |
{ | |
var configuration = new DbMigrationsConfiguration(); | |
configuration.AutomaticMigrationsEnabled = true; | |
configuration.AutomaticMigrationDataLossAllowed = true; | |
var type = context.GetType(); | |
configuration.ContextKey = type.FullName; | |
configuration.ContextType = type; | |
configuration.MigrationsAssembly = type.Assembly; | |
var migrator = new DbMigrator(configuration, context); | |
var f = DbProviderFactories.GetFactory(context.Database.Connection); | |
var n = f.GetType().AssemblyQualifiedName; | |
var tbs = DbProviderFactories.GetFactoryClasses(); | |
var invariant = ""; | |
foreach (DataRow row in tbs.Rows) | |
{ | |
if ((string)row["AssemblyQualifiedName"] != n) continue; | |
invariant = (string)row["InvariantName"]; | |
break; | |
} | |
migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, invariant); | |
migrator.Update(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Automatically migrate your database if you need to