本文介绍了try { 开始事务,savechanges } catch { 回滚,开始另一个事务,savechanges } EF 核心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 _context 的数据库,我想插入一些worker"在名为workers"的表中.帮助我实现这一目标的功能使用后台服务库每两个小时运行一次.我需要保留发生错误时发生的事情的历史记录,因此我设置了一个名为Log"的表.这将填充每个错误或成功.

I have a database named _context and I would like to Insert some "worker" in a table named "workers". The function which help me to achieve that, is running every two hours using the background services library. I need to keep an history of what happened when an error occured, so I set up a table named "Log" which would be fill on each error or success.

所以我尝试:

IDbContextTransaction transac = null;
try
{
   //...
   //code here with _context.workers.toListAsync() etc..
   //...

   foreach (var worker in WorkerList)
   {
      transac = _context.Database.BeginTransaction();
      _context.workers.Add(worker);

      await _context.SaveChangesAsync();
      transac.Commit();

      //LogSuccess
      Log logSuccess = "Worker successfully added";

      _context.Log.Add(logSuccess);
      await _context.SaveChangesAsync();
   }
}
catch(Exception ex)
{
   transac.Rollback();

   //LogErreur
   Log logError = ex.message;

   transac = _context.Database.BeginTransaction();
   _context.Log.Add(logError);
   await _context.SaveChangesAsync();
}

我的问题如下:

_context.SaveChangesAsync() 发生错误时(在添加 worker 之后),它会进入 catch 并开始另一个事务.但是当 _context.SaveChangesAsync 出现时,程序会抛出与之前第一个 _context.SaveChangesAsync() 抛出的错误相同的错误.对我来说,transac.rollback() 应该擦除"之前的交易.

When an error occured on the _context.SaveChangesAsync() (right after the worker is added), it goes in the catch and begin another transaction. But when the _context.SaveChangesAsync comes, the program throw the same error that the first _context.SaveChangesAsync() threw just before. For me, the transac.rollback() should "erase" the previous transaction.

推荐答案

SaveChanges 中的失败不会清除更改跟踪器,因此对 SaveChanges 的后续调用将尝试再次保存所有更改.这使您可以重试暂时性错误或在重试之前修改挂起的更改.

A failure in SaveChanges doesn't clear the Change Tracker, so a subsequent call to SaveChanges will try to save all the changes again. This enables you to retry on transient errors or to modify the pending changes before trying again.

使用新的 DbContext 或调用 ChangeTracker.Clear.

Either use a new DbContext or call ChangeTracker.Clear.

这篇关于try { 开始事务,savechanges } catch { 回滚,开始另一个事务,savechanges } EF 核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:18