apper处理数据并发更新时,需先读取rowversion,再在update脚本中添加where条件,若未成功更新则抛出异常
样例代码:参考:
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
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);