Skip to content

Instantly share code, notes, and snippets.

@adamdriscoll
Created September 28, 2015 22:16
Show Gist options
  • Save adamdriscoll/249dbe4523af19757f3c to your computer and use it in GitHub Desktop.
Save adamdriscoll/249dbe4523af19757f3c to your computer and use it in GitHub Desktop.
Programmatically Determine EF6 Schema Validation Errors
// Programmically get a list of the changes preventing model validation.
// You'll likely see this error:
//Unable to update database to match the current model because there are pending changes and automatic migration is disabled.
//Either write the pending model changes to a code-based migration or enable automatic migration.
//Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
//This is how you can programmatically find out exactly what is preventing the validation
var migrator = new DbMigrator(new vWorkspaceMigrationConfig { TargetDatabase = new DbConnectionInfo("connectionString", "System.Data.SqlClient") });
try
{
migrator.Update();
}
catch (Exception)
{
var differ = typeof(DbMigrator).GetField("_modelDiffer", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(migrator);
var sourceModel = differ.GetType().GetField("_source", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(differ);
var targetModel = differ.GetType().GetField("_target", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(differ);
var diffs = differ.GetType().GetMethod("Diff", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(differ, new[] { sourceModel, targetModel, null, null, null, null });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment