This is part of my method which creates reservations of books:
var book = await _context.Books.FirstOrDefaultAsync(b => b.Id == id);
if (book == null || !book.IsAvailable)
{
return RedirectToAction("Index");
}
var reservation = new Reservation
{
BookId = book.Id,
UserId = user.Id,
ReservedAt = DateTime.Now,
DueDate = DateTime.Now.Date.AddDays(1).AddHours(23).AddMinutes(59).AddSeconds(59),
IsLease = false
};
book.IsAvailable = false;
var rv = Convert.FromBase64String(RowVersion);
_context.Entry(book).Property(b => b.RowVersion).OriginalValue = rv;
try
{
_context.Reservations.Add(reservation);
_context.Books.Update(book);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
ViewData["ErrorMessage"] = "Book already reserved by another user.";
return RedirectToAction("Index", new { searchTitle = searchTitle });
}
And the book model row version property:
[Timestamp]
public byte[] RowVersion { get; set; }
I am trying to have concurrency handled here but the exception when the two users clicks reserve and call this method is never thrown. I have [Timestamp]
attribute for row version in my Book
model and I checked that it is actually changing every time it is updating the book. I also pass this row version from my view in a hidden field where i convert to string. I printed the logs and I see it is actually passed. I don’t know what am I missing here, please help.
I also tried to include AsNoTracking
as in Microsoft tutorial, but it did not change anything.
johny_walker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
It seems the real question is how to implement optimistic concurrency at the API level, not the database. You get optimistic concurrency out of the box as far as the database is concerned, ie between the call to Books.FirstOrDefault
and SaveChanges
. DON’T USE AsNoTracking. Whatever tutorial you read, it was for a different thing.
Once you load the book you already know if the rowversion
is different from the original or not. Instead of trying to get EF to throw, compare the values before doing anything else. if they don’t match, return a 409 – Conflict error with ControllerBase.Conflict :
var book = await _context.Books.FirstOrDefaultAsync(b => b.Id == id);
if (book == null || !book.IsAvailable)
{
return RedirectToAction("Index");
}
//Encode book.RowVersion into a string
//instead of decoding RowVersion into bytes
var stored_rv = Convert.ToBase64String(book.RowVersion);
if(stored_rv!=RowVersion)
{
return Conflict();
}
There’s a standardized way in HTTP to check for version changes and conflicts through the ETag response header and If-Match
and If-No-Match
request headers. The web app fills the ETag response header with a value that’s guaranteed to change if the data changes, eg a checksum or an item version.
In caching scenarios, clients send the ETag they received in the If-None-Match request header. Caches or web apps return new data only if the data has changed. If it hasn’t, they return a 304 – Not Modified response to tell the client to use the data it already has.
In concurrency scenarios, the client sends the ETag
in the If-Match header. If that doesn’t match the server’s value, a 412 – Precondition failed should be returned, although a 409 – Conflict is also valid.
Jeremy Likness explains how all this works in Five RESTFul Web Design Patterns Implemented in ASP.NET Core 2.0 Part 4: Optimistic Concurrency. The concepts are the same in all ASP.NET Core versions, even if the actual calls changed (for the better) in newer versions.
In the action that retrieves the Book
, the rowversion
is added as the ETag :
var etag=Convert.ToBase64String(book.RowVersion);
HttpContext.Response.Headers.Add(HeaderNames.ETag, etag);
In the reservation action, the IfMatch
value is used to check for changes :
if (HttpContext.Request.Headers.ContainsKey(HeaderNames.IfMatch) &&
HttpContext.Request.Headers[HeaderNames.IfMatch].Contains(eTag))
{
return Conflict();
}
...
//Send the new ETag to the client at the end
var etag=Convert.ToBase64String(book.RowVersion);
HttpContext.Response.Headers.Add(HeaderNames.ETag, etag);
In later ASP.NET Core versions you can bind action parameters to headers, eg :
public async Task<IActionResult> Post(...,
[FromHeader(Name = "If-Match")] string? ifMatch,...)
{
...
}
7