Search code examples
c#.netsql-servertransactionstransactionscope

"The operation is not valid for the state of the transaction" error and transaction scope


I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:

The operation is not valid for the state of the transaction

Here is the structure of my calls:

public void MyAddUpdateMethod()
{

    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement

            //do my call to the select statement sp
            bool DoesRecordExist = this.SelectStatementCall(id)
        }
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line
    {
        //create parameters
        //
    }
}

Is the problem with me creating another connection to the same database within the transaction?


Solution

  • After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

    public void MyAddUpdateMethod()
    {
        using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
        {
            using(SQLServer Sql = new SQLServer(this.m_connstring))
            {
                //do my first add update statement            
            }
    
            //removed the method call from the first sql server using statement
            bool DoesRecordExist = this.SelectStatementCall(id)
        }
    }
    
    public bool SelectStatementCall(System.Guid id)
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //create parameters
        }
    }