Skip to content Skip to sidebar Skip to footer

Entity Framework And Sql Server Savepoints

I asked a different question about Nested Transactions and the answer to my question educated me enough to help me realize I was asking the question poorly. So here's a better ques

Solution 1:

This isn't quite a full answer, but I suspect something like this might be going down the right path. My problem is that I'm not entirely sure how to get a SqlTransaction while in a TransactionScope.

///<summary>/// Makes a code block transactional in a way that can be partially rolled-back. This class cannot be inherited.///</summary>///<remarks>/// This class makes use of SQL Server's SAVEPOINT feature, and requires an existing transaction./// If using TransactionScope, utilize the DependentTransaction class to obtain the current Transaction that this class requires.///</remarks>publicsealedclassTransactionSavePoint : IDisposable
{
    publicbool IsComplete { get; protectedset; }
    internal SqlTransaction Transaction { get; set; }
    internalstring SavePointName { get; set; }

    privatereadonly List<ConnectionState> _validConnectionStates = new List<ConnectionState>
                                                                        {
                                                                            ConnectionState.Open
                                                                        };

    publicTransactionSavePoint(SqlTransaction transaction, string savePointName)
    {
        IsComplete = false;
        Transaction = transaction;
        SavePointName = savePointName;

        if (!_validConnectionStates.Contains(Transaction.Connection.State))
        {
            thrownew ApplicationException("Invalid connection state: " + Transaction.Connection.State);
        }

        Transaction.Save(SavePointName);
    }

    ///<summary>/// Indicates that all operations within the savepoint are completed successfully.///</summary>publicvoidComplete()
    {
        IsComplete = true;
    }

    ///<summary>/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.///</summary>publicvoidDispose()
    {
        if (!IsComplete)
        {
            Transaction.Rollback(SavePointName);
        }
    }
}

This would be consumed as such, very similarly to a TransactionScope:

SqlTransaction myTransaction = Foo();

using (var tsp = new TransactionSavePoint(myTransaction , "SavePointName"))
{
  try
  {
    DoStuff();
    tsp.Complete
  }
  catch (Exception err)
  {
    LogError(err);
  }
}

Post a Comment for "Entity Framework And Sql Server Savepoints"