以下是我的事務範圍源代碼的當前體系結構。第三個插入引發了一個.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