【发布时间】:2008-12-04 00:42:27
【问题描述】:
这是我的事务范围源代码的当前架构。第三次插入会引发 .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);
}
}
【问题讨论】:
-
我不想怀疑您的开发技能等,但是您如何测试事务已回滚?交易是否可能正常工作,但您误解了结果。也许发生了其他事情,我们/你在找错树?
标签: c# .net transactions transactionscope