// here, sometimes getting old data or actual data but conflict updates, on multiple calls at the same time
var readyProduct = await _readyProductRepository.FindAsync(p => p.ModelId == readyProductCreate.ModelId);

if (readyProduct == null)
{
    readyProduct = _mapper.Map<ReadyProductCreate, ReadyProduct>(readyProductCreate);

    await _readyProductRepository.AddAsync(readyProduct);
}
else
{
    readyProduct.Count += readyProductCreate.Count;
    _readyProductRepository.Update(readyProduct);
}

var transaction = new ReadyProductTransaction
{
    ModelId = readyProductCreate.ModelId,
    Count = readyProductCreate.Count,
    Status = ReadyProductTransactionType.Import,
    Date = DateTime.Now,
};

await _transactionRepository.AddAsync(transaction);

await _unitOfWork.SaveAsync();

我用隔离级别SerializableTransaction内覆盖了整个过程,但它达到了deadlock.

也许,在插入ReadyProductTransaction表之后创建trigger以更新ReadyProduct表将是一种解决方案,但我想知道是否可以不使用触发器.

DbContext-注册为作用域

所有存储库类,包括UnitOfWork类-注册为作用域

应用程序-.NET5.0

运行在- IIS上的应用程序

推荐答案

Serializable个事务导致死锁的可能性是more,而不是less,因为它们锁定的次数更多,持续时间更长.

这并不意味着您不应该使用它们:更好的隔离总是更有利于数据完整性.你只需要正确地使用它们.

  • 始终确保以相同的顺序锁定表,并try 确保在此类锁中使用相同的索引.
  • Use an Update lock. This prevents deadlocks by gating access to an exclusive lock, while still alowing pure read queries to run.
    In some DBMSs this is called SELECT FOR UPDATE. In SQL Server you add an UPDLOCK hint to a raw SQL query. For example:
var readyProduct = await _dbContext
    .FromSqlRaw<ReadyProduct>("SELECT * FROM dbo.ReadyProduct WITH (UPDLOCK)")
    .Where(p => p.ModelId == readyProductCreate.ModelId)
    .FirstOrDefaultAsync();

话虽如此,请考虑从一开始就不要将数据go 规格化.换句话说,不要将子行的计数存储在父表中.相反,在需要时查询子行的计数(可能使用索引视图).

Csharp相关问答推荐

我们应该如何在IHostedService中使用按请求的GbContent实例?

循环访问Android视图中动态创建的子视图

无法将blob发送到Azure -缺少HTTP标头异常

什么是通过反射创建类的泛型接口方法的正确方法?

如何使用while循环实现异常处理

使页面内容居中

与C#中的Zip列表并行

在路由中使用枚举

使用可信第三方的Iext8.Net pdf签名

如何使用EF Core和.NET 8来upsert到具有多对多关系的表?

将内置的OrderedEumable&Quot;类设置为内部类有什么好处?

在C#.NET项目中启动时,如何等待提升的PowerShell进程退出?

Postgres ENUM类型在第一次运行时对Dapper不可见

Azure Functions v4中的Serilog控制台主题

如何使用.NET Aspire从Blazor应用程序与GRPC API通信?

我是否应该注销全局异常处理程序

如何在C#控制台应用程序中获取用户输入并将其作为订单项目进行处理?

如何在C#.NET桌面应用程序中动态更改焦点工具上的后退 colored颜色

如何将行添加到DataGrid以立即显示它?

如何根据分割文本的块数来计算文本的大小?