dapper 处理并发更新冲突
dapper处理数据并发更新时,需先读取rowversion,再在update脚本中添加where条件,若未成功更新则抛出异常
样例代码:

public async Task<IActionResult> Put(int id, [FromBody] Aircraft model)
{
    byte[] rowVersion;
    if (id != model.Id) 
    {
        return BadRequest();
    }

    using (var connection = new SqlConnection(_connectionString))
    {
        await connection.OpenAsync();
        var query = @"
UPDATE Aircraft 
SET  Manufacturer = @Manufacturer
  ,Model = @Model
  ,RegistrationNumber = @RegistrationNumber 
  ,FirstClassCapacity = @FirstClassCapacity
  ,RegularClassCapacity = @RegularClassCapacity
  ,CrewCapacity = @CrewCapacity
  ,ManufactureDate = @ManufactureDate
  ,NumberOfEngines = @NumberOfEngines
  ,EmptyWeight = @EmptyWeight
  ,MaxTakeoffWeight = @MaxTakeoffWeight
  OUTPUT inserted.RowVer
WHERE Id = @Id
      AND RowVer = @RowVer";
        rowVersion = await connection.ExecuteScalarAsync<byte[]>(query, model);
    }

    if (rowVersion == null) {
        throw new DBConcurrencyException("The entity you were trying to edit has changed. Reload the entity and try again."); 
    }
    return Ok(rowVersion);
}

参考:
https://aspnetmonsters.com/2019/03/2019-03-20-optimistic-concurrency-tracking-with-dapper-and-sql-server/
https://docs.microsoft.com/zh-cn/ef/core/saving/concurrency

相关文章:

  • 2021-08-18
  • 2021-11-10
  • 2021-12-18
  • 2021-08-18
  • 2021-04-02
  • 2022-12-23
猜你喜欢
  • 2021-10-13
  • 2022-03-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
相关资源
相似解决方案