【发布时间】:2020-06-25 07:26:39
【问题描述】:
如.Remove、.Update 或.Add 等每次更改,请致电SaveChangesAsync
using (var transaction = _unitOfWork.BeginTransaction())
{
try
{
var structureProfile = await _unitOfWork.StructureProfiles.GetByStructureIdAsync(id);
if (structureProfile != null)
{
_unitOfWork.StructureProfiles.Remove(structureProfile);
await _unitOfWork.SaveChangesAsync();
}
_unitOfWork.Structures.Remove(structure);
await _unitOfWork.SaveChangesAsync();
await transaction.CommitAsync();
return NoContent();
}
catch (Exception)
{
await transaction.RollbackAsync();
throw;
}
}
或者最后打电话给SaveChangesAsync()?
using (var transaction = _unitOfWork.BeginTransaction())
{
try
{
var structureProfile = await _unitOfWork.StructureProfiles.GetByStructureIdAsync(id);
if (structureProfile != null)
{
_unitOfWork.StructureProfiles.Remove(structureProfile);
//await _unitOfWork.SaveChangesAsync(); -- Remove this part?
}
_unitOfWork.Structures.Remove(structure);
await _unitOfWork.SaveChangesAsync();
await transaction.CommitAsync();
return NoContent();
}
catch (Exception)
{
await transaction.RollbackAsync();
throw;
}
}
【问题讨论】:
-
我们不知道您的代码要做什么,也不知道您的
_unitOfWork是什么类型。请尝试在您的问题中包含相关详细信息,而不仅仅是发布代码墙。 -
DbContext 是一个工作单元。您不需要显式事务或多次调用
SaveChangesAsync。SaveChangesAsync将保留工作单元记录的所有更改,即 DbContext 在内部使用显式事务 -
看起来您尝试实现 Repository anti 模式。这是在像 NHibernate 和 EF 这样的 ORM 变得司空见惯之前使用的 较低级别 抽象。查看 Gunar Peipman 的 No need for Repositories and Unit of Work with EF Core 以获得详细说明,这也解释了为什么您的
Remove可能会执行 10 次插入和 30 次更新 -
至于您的控制器操作,编写它们的正确方法是注入请求范围或瞬态 DbContext(从不单例或长寿命的 DbContext),修改根据需要没有显式事务*的实体,并且在返回之前只调用一次
SaveChangesAsync。 EF 将负责批处理所有更改并在事务中执行它们
标签: c# asp.net-core-3.1 ef-core-3.1