Entity Framework Migrations: Including Go statement only in -Script output

entity-framework, entity-framework-migrations

Solution

internal sealed class Configuration : DbMigrationsConfiguration<Context>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        const string providerInvariantName = "System.Data.SqlClient";
        SetSqlGenerator(providerInvariantName, new BatchingMigrationSqlGenerator(GetSqlGenerator(providerInvariantName)));
    }

    protected override void Seed(Context context)
    {
    }

}

internal class BatchingMigrationSqlGenerator : MigrationSqlGenerator
{
    private readonly MigrationSqlGenerator migrationSqlGenerator;

    public BatchingMigrationSqlGenerator(MigrationSqlGenerator migrationSqlGenerator)
    {
        this.migrationSqlGenerator = migrationSqlGenerator;
    }

    public override IEnumerable<MigrationStatement> Generate(IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)
    {
        var migrationStatements = migrationSqlGenerator.Generate(migrationOperations, providerManifestToken).ToArray();
        foreach (var migrationStatement in migrationStatements)
        {
            migrationStatement.BatchTerminator = "GO";
        }
        return migrationStatements;
    }
}

Problem

As part of planning an Entity Framework migration, in order to debug data movement, I would often use the -Script parameter to generate the script. I could then take this script to Query Analyzer and wrap it in a transaction in order to test it manually. I came across a situation where we needed a Go statement to execute the script properly. The following code was added to the migration in order to output a Go in the proper place. ``` Sql("GO"); ``` This adds a GO statement in the proper position when -Script is used. But when -Script isn't used. I get the exception... ``` System.Data.SqlClient.SqlException (0x80131904): Could not find stored procedure 'GO'. ``` Is there a safe way to add a Go command to the script?

Original source

Related problems