我对EF交易相当新,这是用于保存的代码
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
保存到数据库中。
这是代码的一部分:
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;
}
当我保存项目时,我收到错误:
交易已中止
当我删除事务范围时,保存正常进行!
答案 0 :(得分:2)
您的代码在更改完成保存之前标记了事务已完成:
oContext.SaveChangesAsync();
oScope.Complete();
您需要使用await
:
await oContext.SaveChangesAsync();
oScope.Complete();
如果您处于await
可以在其他线程上恢复的环境中,您可能还需要指定TransactionScopeAsyncFlowOption.Enabled
。