“交易状态无效”错误和事务范围。

86

当我尝试调用包含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
        //
    }
}

在事务中创建另一个到同一数据库的连接是否会出问题?

11个回答

0
给所有来到这个页面的人一个可能的原因:小心异步数据库调用。
这种方法行不通:
//pseudocode
using (new TransactionScope(whatever))
{
    await QueryDatabase();
    //"await" frees up the thread, it goes back into the pool
    //and if other code calls the database again
    //on the freed-up thread, it will fail
}

顺便说一句,最糟糕的是,异常会来自其他代码,你会花几个小时纠结于“为什么完全没有使用事务的代码会抛出这个错误呢?”

你能详细说明一下吗?EF支持像GetAsync、SubmitChangesAsync等异步调用,那你所指的异步/等待有什么问题呢? - undefined
@iBobb,问题已在评论中描述。await会导致线程切换,而TransactionScope与此不兼容。 - undefined
明白了,我一开始并不相信这是真的,但如果没有传递额外的选项,确实会出现问题。它完全兼容,但只有在将TransactionScopeAsyncFlowOption.Enabled传递给TransactionScope的构造函数时才能实现。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接