问题
I have 2 tables enquiry and details. On save button click I have written
fbsave();
fbsavedetails();
fbsave()
save the data in enquiry table and fbsavedetails()
saves data in details table.
now if error occur in fbsavedetails() then both steps should be rollback.
is it possible?
回答1:
You can explicitly create a transaction and pass that around, i.e.
using(var connection = ...)
{
connection.Open();
using (var tran = connection.BeginTransaction())
{
try
{
FBSave(connection, tran);
FBSaveDetails(connection, tran);
tran.Commit();
}
catch
{
tran.Rollback();
throw;
}
}
}
Note that here you must also set the Transaction
on each command, hence why you need to pass it in, and all the commands must be on the same connection object.
Or: you can use TransactionScope
; it is important that the Open()
happens inside the TransactionScope
to get automatic enlistment:
using(var tran = new TransactionScope())
{
FBSave();
FBSaveDetails();
tran.Complete();
}
or:
using(var tran = new TransactionScope())
using(var connection = ...)
{
connection.Open();
FBSave(connection);
FBSaveDetails(connection);
tran.Complete();
}
with the TransactionScope
approach, you don't need to set anything special - most of it is automatic. You can of course optionally pass the connection into the methods, but they could also obtain their own connection, and in most cases it would work fine.
回答2:
You can use TransactionScope.
using(var scope = new TransactionScope())
{
//Complete the transaction only when both inserts succeed.
scope.Complete();
}
if you don't complete the transactionscope it will be rolled back.
回答3:
there are two ways to solve this problem
- use DbTransaction and pass the DbTransaction around the two method, commit the transaction if success and rollback if error happened cons: DbTransaction need to be passed around.
- use TransactionScope pros: ease to use cons: Access is not supported, and if the database is sql2000, msdtc is required to be configured
来源:https://stackoverflow.com/questions/13947274/roll-back-in-c-sharp