C# optimistic concurrency no respond

332 Views Asked by At

I'm trying to add optimistic concurrency to my application by following this tutorial.

Unfortunately the app works as if I haven't changed anything. I open two browsers, in both I edit the same line, overwrite the same value and put it at the first and the other doesn't respond at all. I will save the second and still no warning. I tried to step through it, and with the edit button and when saved, RowVersion changes me. Only SaveChanges() does not throw an exception.

SQL server:

CREATE TABLE [dbo].[Table] (
    [Id]         INT            IDENTITY (1, 1) NOT NULL,
    [RowVersion] ROWVERSION     NULL,
...

Model:

public partial class Table
{
    public int Id { get; set; }

    [Column(TypeName = "timestamp")]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    [MaxLength(8)]
    public byte[] RowVersion { get; set; }

Controller:

[HttpPost]
public ActionResult Table_Edit([Bind(Include = "Id,RowVersion")]Table tab)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Entry(tab).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DbUpdateConcurrencyException ex)
    {
        var entry = ex.Entries.Single();
        Table clientValues = (Table)entry.Entity;
        Table  databaseValues = (Table )entry.GetDatabaseValues().ToObject();
        //changed column
        if (databaseValues.Column_5 != clientValues.Column_5)
            ModelState.AddModelError("Name", "Current value: "
                + databaseValues.Column_5);

        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
            + "was modified by another user after you got the original value. The "
            + "edit operation was canceled and the current values in the database "
            + "have been displayed. If you still want to edit this record, click "
            + "the Save button again. Otherwise click the Back to List hyperlink.");
        tab.RowVersion = databaseValues.RowVersion;
    }

    catch (DataException /* dex */)
    {
        //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
        ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
    }
    return View(tab);
}
0

There are 0 best solutions below