1

As part of my Entity Framework deployment I'm trying to deploy some scripts onto a newly created database, however I got the following error;

ALTER DATABASE statement not allowed within multi-statement transaction.

My Code;

internal sealed class Configuration : DbMigrationsConfiguration<DBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(DBContext context)
    {
        context.Database.ExecuteSqlCommand(
            @"ALTER DATABASE MyDB SET ENABLE_BROKER
            CREATE QUEUE NewCarShareQueue;
            CREATE SERVICE NewCarShareService ON QUEUE NewNewCarShareQueue 
               ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);");
    }
}

I've tried the following as well, making sure only one transaction is going through at once, and not shown here but disposing the current context and recreating it;

internal sealed class Configuration : DbMigrationsConfiguration<DBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(DBContext context)
    {
        context.SaveChanges();
        context.Database.ExecuteSqlCommand(
           @"ALTER DATABASE MyDB SET ENABLE_BROKER");
    }
}

1 Answer 1

2

The Seed command is run after every successful migration run. It actually runs even if no migrations were pending. So it is a bad place to do any altering of the DB structure.

It is better to create a migration and do the ALTERs in there. When your model and migrations are in sync, run add-migration EnableQueue in the PM console. That will give you an empty migration that you can now add your own statements to.

Anyways, running SQL statements in a separate transaction in the Seed method is an interesting problem. Something like this should work (haven't compiled it myself, so there's probably a few typos in it):

protected override void Seed(DBContext context)
{
  using(var tx = new TransactionScope(TransactionScopeOption.RequiresNew))
  using(var conn = new SqlConnection(context.Database.Connection.ConnectionString))
  {
    conn.Open()
    var command = conn.CreateCommand();
    command.CommandText = "ALTER DATABASE WHATEVER YOU WANT TO DO";
    command.ExecuteNonQuery();

    tx.Complete();
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works if you remove the TransactionScope. Otherwise, I got the same error: "ALTER DATABASE statement not allowed within multi-statement transaction"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.