如果context.savechanges()失败,事务内的数据库状态和事务状态会是什么。我可以重用相同的事务但可以创建新的上下文吗?
// Should the retry be at this level in case saveChanges() fail.
using(var transaction = new TransactionScope())
{
// retry at this level in case saveChanges() fail. Use the ambient transaction?
using(var context = new DbContext)
{
//do some update and encounter exception (e.g., concurrency exception.)
context.saveChanges();
}
transaction.Complete();
}
为什么不将context.saveChanges();
包装在try{} catch{}
块中?
using(var transaction = new TransactionScope())
{
// retry at this level in case saveChanges() fail. Use the ambient transaction?
using(var context = new DbContext)
{
//do some update and encounter exception (e.g., concurrency exception.)
int retryCount = 3;
while(retryCount-- >= 0)
{
try
{
context.saveChanges();
transaction.Complete();
}
catch
{
// do what you want to do in case of Save failur
}
}
}
}
如果context.savechanges()失败,事务内的数据库状态和事务状态会是什么。我可以重复使用同一事务但可以创建新的上下文吗?
确切的行为是特定于提供程序且特定于错误的。但是一般的答案是,失败可能会毁灭整个事务,甚至DbContext,因此您无法在事务中进行任意失败操作后重试。它可能适用于并发异常或其他特定的失败,但是您需要作为特殊情况进行测试和处理。