我的web应用程序是使用ASP.NET Core2.2和Pomelo.EntityFrameworkCore.MySql 2.2.0开发的。在PUT请求中,我更新数据库中的一个列。下面的代码是我的演示:
[Produces("application/json")]
[Route("api/{id}/increment/{increment}")]
[HttpPut]
public async Task<IActionResult> PutIncrement([FromRoute] int id, [FromRoute] float increment)
{
Model m = _context.Model
.Where(f => f.Id == id)
.SingleOrDefault();
m.Value += increment;
_context.Entry(m).State = EntityState.Modified;
await _context.SaveChangesAsync();
return Ok(m);
}然后,我与7个CPU并行调用相同的请求(https://localhost/api/1/increment/1) 10次。但是,数据库中的实际值远小于10 (约2-4)。如何在ASP.NET核心中逐一处理请求?
发布于 2019-10-27 12:54:51
您可以实现乐观并发。
乐观并发假设所做的更新将被接受,但在数据库中进行更改之前,记录的原始值将与数据库中的现有行进行比较,如果检测到任何更改,则会引发并发异常。
可以通过添加属性RowVersion来启用它,如下所示
public class Model
{
public int Id {get;set;}
........ // Other Properties
public int Value {get; set;}
[TimeStamp]
public byte[] RowVersion { get; set; }
}RowVersion列将被配置为提供自动行版本控制的数据库类型。
现在,您可以将SaveChangesAsync方法包装在try-catch中,以处理乐观的并发问题。有关更多细节,请查看微软文档。
try
{
// business logic
await _context.SaveChangesAsync();
// Other business logic
}
catch (DbUpdateConcurrencyException ex)
{
// your logic to handle optimistic concurrency.
}https://stackoverflow.com/questions/58579442
复制相似问题