简体   繁体   中英

A transaction problem while executing a C# code

In M code, I am getting an error, "This SqlTransaction has completed; it is no longer usable." The line of code that is generating this code is this sqlTransaction

MSSqlConnectionHandler.CommitTransaction();

This CommitTransaction function is

public static void CommitTransaction()
    {
        try
        {
            _theTran.Commit();
        }
        catch (Exception Ex)
        {
            try
            {
                _theTran.Rollback();
            }
            catch (Exception InnerEx)
            {
                throw InnerEx;
            }
            throw Ex;
        }
    }

But, I Comment out this MSSqlConnectionHandler.CommitTransaction(); line, then no error occured but no data is saved either. What's going wrong, What should I provide here to make it more clear? Thanx in advance

该错误表明事务正在代码中的其他位置提交, _theTran是一个可以在其他地方使用和提交的实例变量吗?

A possbility is the connection that the transaction was on was closed. If that was the case, when this was called:

_theTran.Commit(); 

The error would occur.

Whoever is calling

CommitTransaction

Should do some checking prior to commit, like maybe something like this:

if (conn.State == ConnectionState.Open) 
{
     if (_theTran != null)
     {
          CommitTransaction();
     }
     conn.Close();
}

As far as the exception handling is concerned, the exception handler is doing nothing but rethrowing. IF exception occurs on commit, then try the rollback and always throw. I don't think you need the inner try catch.

try
{             
    _theTran.Commit();         
}         
catch (Exception)
{                        
    _theTran.Rollback();             
    throw;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM