没有竞争条件的ASP.NET Web API中的OData CRUD操作

时间:2021-06-10 19:34:39

In the official guidance for using OData in ASP.NET Web API, the samples that modify the database all appear to contain race conditions. For example, the sample UpdateEntity method calls _context.Products.Any followed by _context.SaveChanges, but the database may have changed between the calls.

在ASP.NET Web API中使用OData的官方指南中,修改数据库的示例似乎都包含竞争条件。例如,示例UpdateEntity方法调用_context.Products.Any,后跟_context.SaveChanges,但数据库可能在调用之间发生了更改。

This differs from the boilerplate code generated by Visual Studio for a new Web API with Entity Framework controller, which contains catches blocks for DbUpdateConcurrencyException. Is there a similar pattern that is a best practice for the OData update methods?

这与Visual Studio为具有Entity Framework控制器的新Web API生成的样板代码不同,后者包含DbUpdateConcurrencyException的捕获块。是否有类似的模式是OData更新方法的最佳实践?

Additionally, calling Any followed by SaveChanges involves two database round trips. Is there a best practice to make only one?

此外,调用Any后跟SaveChanges涉及两次数据库往返。是否有最佳做法只能制作一个?

1 个解决方案

#1


1  

The Any call is just ensuring that the entity that you are trying to update actually exists. You could change that action to,

Any调用只是确保您尝试更新的实体确实存在。您可以将该操作更改为,

protected override Product UpdateEntity(int key, Product update)
{
    try
    {
        _context.Entry(update).State = System.Data.EntityState.Modified;  
        _context.SaveChanges();
        return update;
    }
    catch(DbUpdateConcurrencyException)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

If the entry doesn't exist, SaveChanges() would throw a DbUpdateConcurrencyException.

如果该条目不存在,则SaveChanges()将抛出DbUpdateConcurrencyException。

#1


1  

The Any call is just ensuring that the entity that you are trying to update actually exists. You could change that action to,

Any调用只是确保您尝试更新的实体确实存在。您可以将该操作更改为,

protected override Product UpdateEntity(int key, Product update)
{
    try
    {
        _context.Entry(update).State = System.Data.EntityState.Modified;  
        _context.SaveChanges();
        return update;
    }
    catch(DbUpdateConcurrencyException)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

If the entry doesn't exist, SaveChanges() would throw a DbUpdateConcurrencyException.

如果该条目不存在,则SaveChanges()将抛出DbUpdateConcurrencyException。