我正在尝试按照本教程将乐观并发添加到我的应用程序中。
不幸的是,该应用程序就像我没有改变任何东西一样工作。我打开两个浏览器,在两个浏览器中都编辑同一行,覆盖相同的值并将其放在第一个,而另一个根本没有响应。我将保存第二个,但仍然没有警告。我试图逐步完成它,并使用编辑按钮并在保存时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);
}