在我的Web應用程序中,我必須對用戶操作進行審計。因此,無論何時用戶採取行動,我都會更新採取行動的對象並保持該行動的審計跟蹤。使用亞音速交易
現在,如果我先修改對象,然後更新審計線索但審計線索失敗了,那麼什麼?
顯然我需要回滾更改爲修改後的對象。我可以在簡單的應用程序中使用Sql-Transactions,但我使用Subsonic與db進行通信。我如何處理這種情況?
在我的Web應用程序中,我必須對用戶操作進行審計。因此,無論何時用戶採取行動,我都會更新採取行動的對象並保持該行動的審計跟蹤。使用亞音速交易
現在,如果我先修改對象,然後更新審計線索但審計線索失敗了,那麼什麼?
顯然我需要回滾更改爲修改後的對象。我可以在簡單的應用程序中使用Sql-Transactions,但我使用Subsonic與db進行通信。我如何處理這種情況?
喜歡的東西:
Using ts As New System.Transactions.TransactionScope()
Using sharedConnectionScope As New SubSonic.SharedDbConnectionScope()
' Do your individual saves here
' If all OK
ts.Complete()
End Using
End Using
通過@Kevinw給出的answer是完全沒問題。我只是把他的答案翻譯成C#代碼。我沒有使用註釋,因爲它不會格式化代碼:)另外,我使用try/catch來知道事務是否應該完成或回滾。
using (System.Transactions.TransactionScope ts = new TransactionScope())
{
using (SharedDbConnectionScope scs = new SharedDbConnectionScope())
{
try
{
//do your stuff like saving multiple objects etc. here
//everything should be completed nicely before you reach this
//line if not throw exception and don't reach to line below
ts.Complete();
}
catch (Exception ex)
{
//ts.Dispose(); //Don't need this as using will take care of it.
//Do stuff with exception or throw it to caller
}
}
}
沒有。如果我把SharedDbConnectionScope
以外的變化都在ts.Complete()
之前的數據庫中可見。將其放入服務器,直到操作完成。
我可以確認TransactionScope與SubSonic正常工作,並正確回滾事務。 – kd7 2009-05-26 14:46:22
謝謝@kevinw和@bnkdev。我使用C#,所以我會在C#中發佈代碼,以便其他人可以輕鬆使用它。你也不會把try/catch中的個人保存或行爲放在一起,因此更容易知道是否所有的Ok或不? – TheVillageIdiot 2009-05-27 02:20:41