Reputation: 1
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.
So I try :
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();
}
My problem is the following :
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.
Upvotes: 0
Views: 1612
Reputation: 89386
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.
Either use a new DbContext or call ChangeTracker.Clear.
Upvotes: 3