开发者

How to apply transaction roll back in database object in .net c#

开发者 https://www.devze.com 2023-03-07 09:56 出处:网络
Does anyone know how to apply transaction roll back in database object in .net c#? Example: I have the following code originally:

Does anyone know how to apply transaction roll back in database object in .net c#?

Example: I have the following code originally:

   protected void btnSave_Click(object sender, EventArgs e)
   {
      try {
         m_test = CreateTest();
      } catch{}
   }


   private Db.Test CreateTest()
   {
           var test= new Test();
           test.Title = sTitle.SelectedValue;
           test.FirstName = sFirstName.Text;
           test.LastName = sLastName.Text;
           test.PhoneHome = sHomePhone.Text;
           test.PhoneWork = sWorkPhone.Text;
           test.PhoneMobile = sMobile.Text;
           test.EmailAddress = sEmail.Text;
           test.Save();

           return test;
   }

Then I trying to apply transaction roll back action into the code and applied the following code inside... then I stack under the method CreateTest. I got no 开发者_如何学Pythonidea how could I applied the code for the database object

       protected void btnSave_Click(object sender, EventArgs e)
       {

          SqlConnection connDB = new SqlConnection();
          SqlCommand cmdExecuting = new SqlCommand();

          try {
             connDB = new SqlConnection(connection_string);
             cmdExecuting.Connection = connDB;
             connDB.Open();
             cmdExecuting.Transaction = connDB.BeginTransaction();

             m_test = CreateTest(cmdExecuting);

            if (m_test != 0) {
                 cmdExecuting.Transaction.Rollback();
                 return;
            }
          } catch{}
       }


   private Db.Test CreateTest(SqlCommand  cmdExecuting)
   {
           var test= new Test();
           test.Title = sTitle.SelectedValue;
           test.FirstName = sFirstName.Text;
           test.LastName = sLastName.Text;
           test.PhoneHome = sHomePhone.Text;
           test.PhoneWork = sWorkPhone.Text;
           test.PhoneMobile = sMobile.Text;
           test.EmailAddress = sEmail.Text;
           test.Save();

           return test;
   }

Does anyone know how can I code in the CreateTest() in this case?


Take a look at the TransactionScope class, which provides several benefits including

  • Automatic transaction enlistment of connections made within scope
  • Automatic rollback of transactions when exceptions occur
  • In my opinion it also makes the code a bit more legible since it reduces the amount of code needed

.

try    
{   
    using (TransactionScope scope = new TransactionScope())     
    {                                   
        m_test = CreateTest();          
        scope.Complete(); // Commit transaction     
    }    
}    
catch (Exception ex)    
{
    // Transaction is automatically rolled back
}

Also, see the article Introducing System.Transactions in the .NET Framework 2.0 for a great starting point.


you can take help of the following you dont need to take care of transaction at backend sqltransaction object will take care of it. you can put this code in your own event whichever is responsible for inserting the data in the database

 protected void Button1_Click(object sender, EventArgs e)
    {
      SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;uid=sa;pwd=sa;");
      myConnection.Open();

      // Start a local transaction
      SqlTransaction myTrans = myConnection.BeginTransaction();

      SqlCommand myCommand = new SqlCommand();
      myCommand.Connection = myConnection;
      myCommand.Transaction = myTrans;
      try
      {
        myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
        myCommand.ExecuteNonQuery();
        myCommand.CommandText = "delete * from Region where RegionID=101";

        // Attempt to commit the transaction. 
        myCommand.ExecuteNonQuery();
        myTrans.Commit();
        Response.Write("Both records are written to database.");
      }
      catch (Exception ep)
      {
        // Attempt to roll back the transaction. 
        myTrans.Rollback();
        Response.Write(ep.ToString());
        Response.Write("Neither record was written to database.");
      }
      finally
      {
        myConnection.Close();
      }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消