I am using SqlTransaction
s 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 datareader
s 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 datareader
s within a sqltransaction
??
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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();
}