以下是我的事务范围源代码的当前体系结构。第三个插入引发了一个.NET异常(不是SQL异常),它不回滚前两个插入语句。我做错了什么?TransactionScope不回滚事务
编辑:我删除了从insert2和insert3的try/catch。我还从insert1 try/catch中删除了异常处理实用程序,并将“throw ex”。它仍然不会回滚事务。
编辑2:我在Insert3方法中添加了try/catch,并在catch语句中添加了“throw”。它仍然不会回滚事务。
UPDATE:根据我收到的反馈意见中,“提供SQLHelper”类使用SqlConnection对象建立与数据库的连接,然后创建一个SqlCommand对象,设置CommandType属性,以“StoredProcedure的”调用ExecuteNonQuery方法的SqlCommand。
我也没有将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);
}
}
我不想质疑你的开发技能等,但你如何测试交易已经回滚?交易是否可以正常运行,但是您误解了结果。也许其他事情正在发生,我们/你在咆哮着错误的树? – 2008-12-04 23:26:43
希望这有助于:http://stackoverflow.com/questions/28191333/error-in-ambient-transaction-doesnt-rollback-the-transaction/28258935#28258935 – 2015-09-06 04:02:56