在我的应用程序中,我有两种方法: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
选项,并在update方法中编写如下内容:
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;
}
我的代码是否正确?
答案 0 :(得分: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对象的初始化可以在单独的方法中完成,以便重用。
如果这不能解决您的问题,请发表评论。