Roll back in c#

亡梦爱人 提交于 2020-01-01 08:49:07

问题


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

  1. 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.
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!