EF中的BeginTransaction

时间:2012-07-15 11:12:08

标签: c# winforms sql-server-2008 entity-framework-4

我希望在EF中使用Transaction。但我对此一无所知。

请将此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();

    }

thx

1 个答案:

答案 0 :(得分:2)

您可以在EntityFramework中使用TransactionScope类进行交易:

 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();
    }
}