问题
In my web application I've to keep audit of the user actions. So whenever user takes an action I update the object on which action is taken and keep audit trail of that action.
Now If I first modify the object and then update audit trail but the audit trail fails then what?
Obviously I need to roll-back changes to modified object. I can use Sql-Transactions in simple application, but I'm using Subsonic to talk to db. How I can handle the situation?
回答1:
Something like:
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
回答2:
The answer given by @Kevinw is perfectly okay. I'm posting this just as translation of his answer to C# code. I'm not using comments as it will not format code :) Also I'm using try/catch to know if transaction should complete or be rolled back.
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
}
}
}
回答3:
Nope. If I put the SharedDbConnectionScope
outside the changes are visibles in the database before ts.Complete()
. Putting it inside blocks the server until the operation is done.
来源:https://stackoverflow.com/questions/910863/using-transactions-with-subsonic