I am working on an ASP.NET MVC project with EF in C# from a book and this part is to avoid updating an entity concurrently from different sessions. The book is great but unfortunately in this part the explanation is not sufficient and I would appreciate if someone could help me understand. I will try to omit irrelevant code. The model basically has only one property "Name" so it is really simple:
[HttpPost]
public ActionResult Edit(int? id, byte[] rowVersion)
{
string[] fieldsToBind = new string[] { "Name", "RowVersion" };
var categoryToUpdate = db.Categories.Find(id);
if (TryUpdateModel(categoryToUpdate, fieldsToBind))
{
try
{
db.Entry(categoryToUpdate).OriginalValues["RowVersion"] =
rowVersion;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DbUpdateConcurrencyException ex)
{//... and the code goes on to handle the concurrent update
// scenario
}
Here is what I don't understand: If the TryUpdateModel method successfully updated the model, and bound the new values "Name" and "RowVersion" (that were provided by the view) why do I have to include this line: db.Entry(categoryToUpdate).OriginalValues["RowVersion"] = rowVersion;? What does this line do exactly? Why is it required for the exception to be thrown? Thanks