包含在 TransactionScope 中时是否覆盖 SaveChangesAsync? [英] Overriding SaveChangesAsync when enclosed inside TransactionScope?
问题描述
我对EF事务还很陌生,这是用于保存的代码
I'm fairly new to EF transactions, this is the code that is used for saving
public bool Save(TbArea area, bool isNew, out string errMsg)
{
try
{
errMsg = string.Empty;
using (var oScope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(120)))
{
try
{
TbArea oEntity = oContext.TbArea.Where(a => a.AreaCode == area.AreaCode && a.CompanyId == MainClass.SystemCompanyId).FirstOrDefault();
if (oEntity != null)
{
if (isNew) { errMsg = Resources.ResSales.MsgRecordCodeDublicated; return false; }
oContext.TbArea.Attach(oEntity);
oContext.Entry(oEntity).CurrentValues.SetValues(area);
}
else
{
if (!isNew) { errMsg = Resources.ResSales.MsgRecordNotFoundInDB; return false; }
oContext.TbArea.Add(area);
}
oContext.SaveChangesAsync();
oScope.Complete();
return true;
}
catch (Exception ex)
{
oScope.Dispose();
errMsg = ex.Message;
return false;
}
}
我正在覆盖 SaveChangesAsync
这样我就可以将 ChangeTracker.Entries
保存到数据库中.这是代码的一部分:
I'm overriding SaveChangesAsync
so that I can save the ChangeTracker.Entries
into the database.
this is a portion of the code:
dbContext.AcceptAllChanges();
logsSet.AddRange(audits);
int result = 0;
try
{
result = await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
//scope.Complete(); there was a transaction that I commented out, I thought it might overlaps the original transaction!
return result;
}
catch (Exception ex)
{
var m = ex.Message;
return result;
}
当我保存项目时,出现错误:
When I save an item, I get the error :
事务已中止
当我删除事务范围时,保存正常发生!
when I remove the transaction scope the saving happens normally!
推荐答案
在更改完成保存之前,您的代码正在将事务标记为完成:
Your code is marking the transaction complete before the changes have finished saving:
oContext.SaveChangesAsync();
oScope.Complete();
你需要使用await
:
await oContext.SaveChangesAsync();
oScope.Complete();
如果您处于 await
可以在不同线程上恢复的上下文中,您可能还需要指定 TransactionScopeAsyncFlowOption.Enabled
.
If you're in a context where await
can resume on a different thread, you'll probably also need to specify TransactionScopeAsyncFlowOption.Enabled
.
这篇关于包含在 TransactionScope 中时是否覆盖 SaveChangesAsync?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!