0

我问了一个关于嵌套事务的不同问题,我的问题的答案足以让我意识到我问的问题很糟糕。所以这是一个更好的问题。

如何使用基于 Entity Framework 4.0 构建的 DAL有效地实现 SQL Server 保存点(链接 1链接 2 )?

我想编写以下代码并让它以 SQL Server 的 SAVEPOINTS 的方式工作

public void Bar()
{
  using (var ts = new TransactionScope())
  {
    var ctx = new Context();
    DoSomeStuff(ctx);

    bool isSuccessful;

    using (var spA = new SavePoint("A")) // <-- this object doesn't really exist, I don't think
    {
      isSuccessful = DoSomeOtherStuff(ctx);
      if (isSuccessful)
        spA.Complete(); // else rollback bo prior to the beginning of this using block
    }

    Log(ctx, isSuccessful);

    ts.Complete();
  }
}

有没有这样一种方法可以做任何与此类似的事情,或者其他与 EF4 配合得很好的事情?(我们使用自定义的自我跟踪 POCO 实体)

4

1 回答 1

0

这不是一个完整的答案,但我怀疑这样的事情可能会走上正确的道路。我的问题是我不完全确定如何在 TransactionScope 中获取 SqlTransaction

/// <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>
public sealed class TransactionSavePoint : IDisposable
{
    public bool IsComplete { get; protected set; }
    internal SqlTransaction Transaction { get; set; }
    internal string SavePointName { get; set; }

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

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

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

        Transaction.Save(SavePointName);
    }

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

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

这将像这样被消耗,与 TransactionScope 非常相似:

SqlTransaction myTransaction = Foo();

using (var tsp = new TransactionSavePoint(myTransaction , "SavePointName"))
{
  try
  {
    DoStuff();
    tsp.Complete
  }
  catch (Exception err)
  {
    LogError(err);
  }
}
于 2011-08-09T02:03:04.740 回答