我正在尝试通过遵循this tutorial向我的应用程序添加开放式并发。
不幸的是,该应用程序可以正常运行,好像我没有进行任何更改一样。我打开两个浏览器,在两个浏览器中我编辑同一行,覆盖相同的值,然后将其放在第一个,而另一个根本不响应。我将保存第二个,但仍然没有警告。我尝试逐步进行操作,并使用“编辑”按钮和保存后的RowVersion
更改了我。只有SaveChanges()
不会引发异常。
SQL服务器:
CREATE TABLE [dbo].[Table] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[RowVersion] ROWVERSION NULL,
...
型号:
public partial class Table
{
public int Id { get; set; }
[Column(TypeName = "timestamp")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[MaxLength(8)]
public byte[] RowVersion { get; set; }
控制器:
[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);
}