【问题标题】:Update database with nested transactions scope使用嵌套事务范围更新数据库
【发布时间】:2016-07-01 09:52:52
【问题描述】:

在我的应用程序中,我有两种方法:GetPaymentToDateRemovePayment

public Payment RemovePayment(int paymentId)
{
    Payment payment;
    using (var transaction = new TransactionScope(TransactionScopeOption.RequiresNew,
        new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
    {
        //some staff
        m_staffContext.SaveChanges();
        transaction.Complete();
    }
    return payment;
}

public Payment GetPaymentToDate(DateTime paymentDate)
{
    var payment = new Payment
    {
        //initialize properties
    };
    using (var transaction = new TransactionScope(TransactionScopeOption.RequiresNew,
        new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
    {
        m_staffContext.Payments.Add(payment);
        m_staffContext.SaveChanges();
        transaction.Complete();
    }
    return payment;
}

不,我需要实现 Update 方法。这种方法的逻辑是删除旧的,然后创建一个新的支付。因此,如果另一个失败,我想在一个父事务范围和角色返回嵌套事务中执行此操作。我要从现有方法中删除 TransactionScopeOption.RequiresNew 选项,并在更新方法中写下这样的内容:

public Payment UpdatePayment(int paymentId)
{
    Payment newPayment;
    using (var transaction = new TransactionScope(TransactionScopeOption.RequiresNew,
        new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
    {
        var removedPayment = RemovePayment(paymentId);
        var newPayment = GetPaymentToDate(removedPayment.Date);
        m_staffContext.SaveChanges();
        transaction.Complete();
    }
    return newPayment;        
}

我的代码是否正确?

【问题讨论】:

  • 为什么每个事务范围都有RequiresNew?默认值就可以了。

标签: c# database transactionscope


【解决方案1】:

您不应该调用这些方法,而是使用如下块实现更新付款中的实际逻辑:

using( var transaction = .....)
{
   var payment = m_staffContext.Payments.Get(paymentId);
   m_staffContext.Payments.Remove(payment);
   m_staffContext.Payments.Add(payment);
   m_staffContext.SaveChanges();
}

但是你为什么不只更新现有的付款。 在 AddNewPayment 方法中,Payment 对象的初始化可以在单独的方法中完成,以便重复使用。

如果这不能解决您的问题,请发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多