代码之家  ›  专栏  ›  技术社区  ›  Michael Kniskern

“操作对事务状态无效”错误和事务范围

  •  50
  • Michael Kniskern  · 技术社区  · 16 年前

    尝试调用包含select语句的存储过程时,出现以下错误:

    该操作对于事务的状态无效

    以下是我的电话结构:

    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
            //
        }
    }
    

    我在事务中创建到同一数据库的另一个连接时出现问题吗?

    5 回复  |  直到 6 年前
        1
  •  47
  •   Michael Kniskern    9 年前

    在做了一些研究之后,似乎我不能用TransactionScope块打开同一数据库的两个连接。我需要修改我的代码,使其看起来像这样:

    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
        }
    }
    
        2
  •  8
  •   Sharique    14 年前

    我也遇到了同样的问题,我把事务超时改为15分钟,它就工作了。 我希望这有帮助。

    TransactionOptions options = new TransactionOptions();
    options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
    options.Timeout = new TimeSpan(0, 15, 0);
    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))
    {
        sp1();
        sp2();
        ...
    
    }
    
        3
  •  7
  •   R. Schreurs Rohith    13 年前

    当我遇到这个异常时,有一个innerException“事务超时”。因为这是在调试会话期间,当我在TransactionScope内暂停代码一段时间时,我选择忽略这个问题。

    当这个带有超时的特定异常出现在部署的代码中时,我认为.config文件中的以下部分将帮助您:

    <system.transactions> 
            <machineSettings maxTimeout="00:05:00" /> 
    </system.transactions>
    
        4
  •  2
  •   Wyatt    16 年前

    当我的事务嵌套在另一个事务中时,我遇到了这个错误。存储过程是否可能声明自己的事务,或者调用函数是否声明了一个事务?

        5
  •  0
  •   Vishav Premlall    6 年前

    对于我来说,当我在另一个事务块内遇到异常后试图回滚事务块时,出现了这个错误。

    我要做的就是移除我的内部事务块。

    当使用嵌套事务时,事情可能会变得非常混乱,最好避免这种情况并重新构造代码。