处理交易错误的最佳方式?
Best way to handle transaction errors?
在 Asp.net 核心和 entity framework 中处理事务错误的最佳方法是什么?
此时我带来了类似的东西:
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);
}
}
但真的不知道这是否是一个好习惯。你会怎么做?
我认为你的代码很好,除了你不需要调用:
await transaction.RollbackAsync();
在 catch 块中。处理失败的事务会自动回滚。
Link: https://docs.microsoft.com/en-us/ef/core/saving/transactions
您处理交易的方式没有问题,但您可以在此处进行一些改进:
- 从您的控制器中删除数据访问代码并将其移至单独的 class。
- 不要return错误的技术细节,而是用户友好的消息。
- AddAsync 仅适用于特殊用例,所有其他情况应使用非异步方法 Add。
来自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."
在 Asp.net 核心和 entity framework 中处理事务错误的最佳方法是什么?
此时我带来了类似的东西:
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);
}
}
但真的不知道这是否是一个好习惯。你会怎么做?
我认为你的代码很好,除了你不需要调用:
await transaction.RollbackAsync();
在 catch 块中。处理失败的事务会自动回滚。
Link: https://docs.microsoft.com/en-us/ef/core/saving/transactions
您处理交易的方式没有问题,但您可以在此处进行一些改进:
- 从您的控制器中删除数据访问代码并将其移至单独的 class。
- 不要return错误的技术细节,而是用户友好的消息。
- AddAsync 仅适用于特殊用例,所有其他情况应使用非异步方法 Add。
来自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."