Mic*_*ern 12 .net c# transactions transactionscope
这是我的事务范围源代码的当前体系结构.第三个插件抛出.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);
}
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 25
我也遇到过类似的问题.我的问题发生是因为我在SqlCommands中使用的SqlConnection在创建TransactionScope之前已经打开,所以它从未作为事务登记在TransactionScope中.
在您输入TransactionScope块之前,SqlHelper类是否可能重用已打开的SqlConnection实例?
看起来你在Insert3()中捕获异常,所以你的代码在调用后继续.如果你想要它回滚,你需要让异常冒泡到主例程中的try/catch块,以便永远不会调用ts.Complete()语句.
| 归档时间: |
|
| 查看次数: |
16179 次 |
| 最近记录: |