1
votes

Background

We work in a geographically distributed team. Every so often, a team on the other side of the world creates a build for the integration server that fails due to

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.

We use code based migrations.

To simplify trouble shooting, I'm looking for a method to display what automatic automatic migration would have been applied, were automatic migrations allowed, from code. The environment to script new migrations does not exist on the integration server, where the problem manifests.

Attempted Solution

I attempted to use DbMigrator as outlined here, but that seems to only display code based migrations that have not yet been applied.

Question

Is there a code-based method that will display the changes that would be applied, were automatic migrations enabled?

1

1 Answers

1
votes

Here is a solution that worked for me

public string GetAutomaticMigrationsScript<T>() where T : DbMigrationsConfiguration, new()
{
    var configuration = new T();
    configuration.AutomaticMigrationDataLossAllowed = true;
    configuration.AutomaticMigrationsEnabled = true;
    var migrator = new DbMigrator(configuration);
    var scriptor = new MigratorScriptingDecorator(migrator);
    var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);

    return script;
}

Usage:

Console.WriteLine(GetAutomaticMigrationsScript<MyConfiguration>());

The variable script will contain the SQL Script that would be run to perform an automatic migration. This code will not actually perform the migration, but you can paste the contents of script into SSMS and run the migration there.