我是相當新的EF交易,這是用於保存當在TransactionScope中放置時覆蓋SaveChangesAsync?
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;
}
當我保存一個項目,我得到的錯誤:
交易已中止
當我刪除事務範圍保存正常發生!
你爲什麼提到時間戳?這是一個日誌運行操作? –
不,我刪除它,仍然得到相同的錯誤 –
我將TransactionScope移動到重寫的方法,現在它的工作 –