Reputation: 41698
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.
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?
Additionally, calling Any
followed by SaveChanges
involves two database round trips. Is there a best practice to make only one?
Upvotes: 1
Views: 1533
Reputation: 6793
The Any call is just ensuring that the entity that you are trying to update actually exists. You could change that action to,
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
.
Upvotes: 1