这是我事务范围源代码的当前架构。第三次插入引发了.NET异常(不是SQL异常),并且没有回滚前面的两个插入语句。我做错了什么?
编辑:我从insert2和insert3中移除了try/catch。我还从insert1的try/catch中移除了异常处理实用程序,并替换成了“throw ex”。它仍然没有回滚事务。
编辑2:我在Insert3方法上添加了try/catch,并在catch语句中放置了一个“throw”。它仍然没有回滚事务。
更新:根据我收到的反馈,“SqlHelper”类使用SqlConnection对象建立与数据库的连接,然后创建一个SqlCommand对象,将CommandType属性设置为“StoredProcedure”,并调用SqlCommand的ExecuteNonQuery方法。
我也没有在当前连接字符串中添加Transaction Binding=Explicit Unbind。我会在下次测试时添加。
public void InsertStuff()
{
try
{
using(TransactionScope ts = new TransactionScope())
{
//perform insert 1
using(SqlHelper sh = new SqlHelper())
{
SqlParameter[] sp = { /* create parameters for first insert */ };
sh.Insert("MyInsert1", sp);
}
//perform insert 2
this.Insert2();
//perform insert 3 - breaks here!!!!!
this.Insert3();
ts.Complete();
}
}
catch(Exception ex)
{
throw ex;
}
}
public void Insert2()
{
//perform insert 2
using(SqlHelper sh = new SqlHelper())
{
SqlParameter[] sp = { /* create parameters for second insert */ };
sh.Insert("MyInsert2", sp);
}
}
public void Insert3()
{
//perform insert 3
using(SqlHelper sh = new SqlHelper())
{
SqlParameter[] sp = { /*create parameters for third insert */ };
sh.Insert("MyInsert3", sp);
}
}