-3

我想在 EF 中使用事务。但我对此一无所知。

请将此 ADO 代码转换为 EF:

using System.Data.SqlClient;
private void button4_Click(object sender, EventArgs e)
    {
        string strConnection = @"Data Source = ARASH-PC\ARASH; Initial Catalog = SampleDB; User Id = sa; Password = 1;";
        SqlConnection con = new SqlConnection(strConnection);
        con.Open();
        SqlCommand command1 = new SqlCommand("INSERT " + " INTO Acc_Group (SalMali,Code_Group,Name_Group)" + " VALUES(84,60,N'aaaa')", con);
        SqlCommand command2 = new SqlCommand("INSERT " + " INTO Acc_Group (SalMali,Code_Group,Name_Group)" + " VALUES(84,80,N'ssss')", con);

        SqlTransaction Transaction = con.BeginTransaction();
        command1.Transaction = Transaction;
        command2.Transaction = Transaction;
        command1.ExecuteNonQuery();
        command2.ExecuteNonQuery();
        Transaction.Save("This Point");
        Transaction.Rollback("This Point");
        Transaction.Commit();
        command1.Dispose();
        command2.Dispose();
        con.Close();

    }

谢谢

4

1 回答 1

2

您可以使用 TransactionScope 类在 EntityFramework 中使用事务:

 using (TransactionScope transaction = new TransactionScope())
            {
            }

我编辑了我的答案:

 ExamoleEntities context= new ExamoleEntities ();
 bool success = false;
 using (TransactionScope transaction = new TransactionScope())
   {
     try
     {
        //your Code Here
        //
        context.SaveChanges(...);
        transaction.Complete();
        success = true;
     }
     catch (Exception ex)
     {
       // Handle errors and rollback here and retry if needed.
       // retry, otherwise stop the execution.
       Console.WriteLine("An error occured. "
                            + "The operation cannot be retried."
                            + ex.Message);                                
      }
 if (success)
        {

            context.AcceptAllChanges();
        }
        else
        {
            Console.WriteLine("Error");
        }
        context.Dispose();
    }
}
于 2012-07-15T11:19:57.240 回答