Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Scripts from dotnet with transactions

I have been trying to execute sql scripts from dotnet (C#) but the sql scripts could contain GO statements and I would like to be able to wrap the collection of scripts in a transaction.

I found this question and the accepted answer got me going for handling the GO statements, but if I use a BeginTransaction it throws a InvalidOperationException at the "new ServerConnection" line.

SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlTransaction transaction = connection.BeginTransaction(transactionName);
ServerConnection serverConnection = new ServerConnection(connection);

I am running this against a SQL 2005 server.

like image 395
benPearce Avatar asked Aug 06 '26 16:08

benPearce


1 Answers

I found a way, after trying several combinations, the simplest one worked...

Well this is assuming you are using a TransactionScope object

using (
    var transactionScope = new TransactionScope(TransactionScopeOption.Required,
                                                new TransactionOptions
                                                    {
                                                        IsolationLevel =
                                                            IsolationLevel.ReadCommitted,
                                                        Timeout = TimeSpan.FromMinutes(300)
                                                    }))
{
    sqlServerInstance.ConnectionContext.SqlExecutionModes = SqlExecutionModes.ExecuteAndCaptureSql;
    sqlServerInstance.ConnectionContext.StatementTimeout = int.MaxValue;

    //This line makes the MAGIC happen =)
    sqlServerInstance.ConnectionContext.SqlConnectionObject.EnlistTransaction(Transaction.Current);
    sqlServerInstance.ConnectionContext.ExecuteNonQuery(scriptContent);
}
like image 165
Jupaol Avatar answered Aug 08 '26 12:08

Jupaol