How to use transactions with the Entity Framework?

前端 未结 5 504
说谎
说谎 2020-12-13 13:47

When you have code like this:

Something something = new Something();
BlahEntities b = new BlahEntities()    
b.AddToSomethingSet(something);
b.SaveChanges();         


        
5条回答
  •  醉酒成梦
    2020-12-13 14:20

    using System.Transactions;
    
    using (TransactionScope scope = new TransactionScope())
    {
        try
        {
            using(DataContext contextObject = new DataContext(ConnectionString))
            {
                contextObject.Connection.Open();
                // First SaveChange method.
                contextObject.SaveChanges();
    
                // Second SaveChange method.
                contextObject.SaveChanges();
                //--continue to nth save changes
    
                // If all execution successful
                scope.Complete();   
           }
        }
        catch(Exception ex)
        {
            // If any exception is caught, roll back the entire transaction and end the scope.
            scope.Dispose();
        }
        finally
        {
            // Close the opened connection
            if (contextObject.Connection.State == ConnectionState.Open)
            {
                contextObject.Connection.Close();
            }
        }
    }
    

    Find the link below for detailed explanation https://msdn.microsoft.com/en-us/data/dn456843.aspx

提交回复
热议问题