【发布时间】:2016-07-01 09:52:52
【问题描述】:
在我的应用程序中,我有两种方法:GetPaymentToDate 和 RemovePayment:
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