Using datareaders with sqltransactions

2019-06-08 02:27发布

I am using SqlTransactions in my code for roll back purpose. Within the transaction I got multiple statements to be executed with may include selects inserts and updates. All these statements are within the scope of the sqltransaction. Everything works fine just for one problem. I am using datareaders for select statements . And these readers are closed once they are used. This forces the connection to be lost and every thing fails. Does any one have a solution on whether I can use datareaders within a sqltransaction??

2条回答
等我变得足够好
2楼-- · 2019-06-08 02:50

You should open the SqlConnection by itself.
The SqlDataReader doesn't close the SqlConnection when you close the DataReader

For example:

using(SqlConnection cn = GetConnection())
{
    cn.Open();
    SqlTransaction tr = cn.BeginTransaction("myTransaction");
    .....

    SqlCommand command = new SqlCommand(sqlString, cn);

    using(SqlDataReader reader = command.ExecuteReader())
    {
        .....
    }

    SqlCommand command1 = new SqlCommand(sqlString1, cn);
    using(SqlDataReader reader1 = command1.ExecuteReader())
    {
        .....
    }
    tr.Commit();
}
查看更多
地球回转人心会变
3楼-- · 2019-06-08 03:02

A DataReader will only close the connection if the CommandBehavior.CloseConnection option was set when calling ExecuteReader.

You should be OK if you avoid setting this option.

查看更多
登录 后发表回答