[英]How many times to call .SaveChangesAsync() in .BeginTransaction() EF Core 3.1
Call SaveChangesAsync
every changes like .Remove
, .Update
or .Add
调用
SaveChangesAsync
每个更改,例如.Remove
、 .Update
或.Add
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;
}
}
Or Call SaveChangesAsync()
at last part?还是在最后部分调用
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;
}
}
In your case, with a single method performing the entire unit of work, you don't need the transaction: SaveChangesAsync
will perform the actual queries as a single transaction.在您的情况下,使用单个方法执行整个工作单元,您不需要事务:
SaveChangesAsync
将作为单个事务执行实际查询。
Transactions become useful, for example, when the work is spread across multiple methods that each take responsability for their own part of it, including their own SaveChangesAsync
.事务变得有用,例如,当工作分布在多个方法中时,每个方法都对自己的部分负责,包括他们自己的
SaveChangesAsync
。 Then, either you explicitly commit the transaction eventually, or you dispose of its object, causing it to be rolled back.然后,要么您最终显式提交事务,要么处置其 object,导致它回滚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.