ASP.NET Core & EF Core : concurrency exception not thrown despite working rowversion

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.

New contributor

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật