简体   繁体   中英

what is there equivalent to rollback transaction of SQL in c#?

if in a transaction any error occurs

sql will rollback the process.

BEGIN TRANSACTION

 COMMIT

 IF @@TRANCOUNT > 0
        ROLLBACK

END TRANSACTION

How i can do the same in asp.net C#?

Check below to see how to implement Implicit Transaction using Transaction Scope which will give you transaction in C#. If you call the Complete method for the TransactionScope it will be commited otherwise rolledback.

http://msdn.microsoft.com/en-us/library/ee818746(v=vs.110).aspx

The following snippet shows the general idea:

using (SqlConnection connection = new SqlConnection("connection string"))
using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlCommand command = new SqlCommand("command text", connection) { Transaction = transaction })
{
    connection.Open();
    try
    {
        command.ExecuteNonQuery();
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
}

If the command fails to execute and throws any exception, the transaction will be rolled back.

I don't really find your question clear enough. Here is something I would like to share. I assume you are asking this.

In SQL, imagine something like this (not really syntax):

begin transaction
insert into table X y= 1, z =2
insert into table A b =1, c =2
commit

Now, imagine there is no column b in table A so this transaction would not work.

To do same in ASP.Net where you have close to no control over actual DB transactions, combination of try/catch and transaction is what I will suggest. Not because it is the right way but just because it can do what you want.

Again, this is not the right way. Tell more about your problem and more people can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM