Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.89 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. BeginTransaction in EF [closed]
  2. using System.Data.SqlClient;
  3. private void button4_Click(object sender, EventArgs e)
  4.     {
  5.         string strConnection = @"Data Source = ARASH-PCARASH; Initial Catalog = SampleDB; User Id = sa; Password = 1;";
  6.         SqlConnection con = new SqlConnection(strConnection);
  7.         con.Open();
  8.         SqlCommand command1 = new SqlCommand("INSERT " + " INTO Acc_Group (SalMali,Code_Group,Name_Group)" + " VALUES(84,60,N'aaaa')", con);
  9.         SqlCommand command2 = new SqlCommand("INSERT " + " INTO Acc_Group (SalMali,Code_Group,Name_Group)" + " VALUES(84,80,N'ssss')", con);
  10.  
  11.         SqlTransaction Transaction = con.BeginTransaction();
  12.         command1.Transaction = Transaction;
  13.         command2.Transaction = Transaction;
  14.         command1.ExecuteNonQuery();
  15.         command2.ExecuteNonQuery();
  16.         Transaction.Save("This Point");
  17.         Transaction.Rollback("This Point");
  18.         Transaction.Commit();
  19.         command1.Dispose();
  20.         command2.Dispose();
  21.         con.Close();
  22.  
  23.     }
  24.        
  25. using (TransactionScope transaction = new TransactionScope())
  26.             {
  27.             }
  28.        
  29. ExamoleEntities context= new ExamoleEntities ();
  30.  bool success = false;
  31.  using (TransactionScope transaction = new TransactionScope())
  32.    {
  33.      try
  34.      {
  35.         //your Code Here
  36.         //
  37.         context.SaveChanges(...);
  38.         transaction.Complete();
  39.         success = true;
  40.      }
  41.      catch (Exception ex)
  42.      {
  43.        // Handle errors and rollback here and retry if needed.
  44.        // retry, otherwise stop the execution.
  45.        Console.WriteLine("An error occured. "
  46.                             + "The operation cannot be retried."
  47.                             + ex.Message);                                
  48.       }
  49.  if (success)
  50.         {
  51.  
  52.             context.AcceptAllChanges();
  53.         }
  54.         else
  55.         {
  56.             Console.WriteLine("Error");
  57.         }
  58.         context.Dispose();
  59.     }
  60. }