Reputation: 6296
What's the best way to handle transaction errors in Asp.net core and entity framework?
At this time I have come with something like:
using (var transaction = _dbContext.Database.BeginTransaction())
{
try
{
await _dbContext.MyTable1.AddAsync(table1Entity);
await _dbContext.SaveChangesAsync();
Entity2 e2 = new Entity2();
e2.Table1Id = table1Entity.Id;
await _dbContext.SaveChangesAsync();
await transaction.CommitAsync();
return new CreatedAtRouteResult(...);
}
catch (Exception ex)
{
System.Console.Write(ex);
await transaction.RollbackAsync();
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
}
But don't really know if this is a good practice. How would you do this?
Upvotes: 1
Views: 1268
Reputation: 757
There is nothing wrong with the way you are handling the transactions, but there are some improvements you can make here:
From the EF docs:
"This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used."
Upvotes: 1
Reputation: 71
I think your code was good, except you don't need to call:
await transaction.RollbackAsync();
in catch block. Failed transaction will auto-rollback when disposed.
Link: https://learn.microsoft.com/en-us/ef/core/saving/transactions
Upvotes: 1