我正在应用rowVersion列来解决并发问题。
为了测试这些更改,我运行我的应用程序并打开两个不同的选项卡。在第一个选项卡上,我编辑一个字段,然后在第二个选项卡上,我编辑该字段。然后,将更改保存在第一个浏览器中,并得到DBUPdateConcurrency
异常。即使我关闭另一个选项卡并仅在第一个浏览器上进行更改,它仍然会返回DBUPdateConcurrency
异常。请参见下面的代码:
课程
public int CustomerID { get; set; }
public string Comment { get; set;}
[Timestamp]
public byte[] RowVersion { get; set; }
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomerDetail model)
{
if (ModelState.IsValid)
{
int customerID = model.CustomerID;
string comment = model.Comment;
byte[] rowVersion = model.RowVersion;
using (BusinessLogicLayer BLL = new BusinessLogicLayer())
{
try
{
Customer customer =
BLL.GetSingleCustomer(customerID);
BLL.customerDB_entity.Entry(customer)
.OriginalValues["RowVersion"] = rowVersion;
BLL.UpdateCustomer(customerID);
BLL.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseEntry = entry.GetDatabaseValues();
if (databaseEntry == null)
{
ModelState.AddModelError(
string.Empty,
"Unable to save changes. The field was deleted by another user.");
}
else
{
ModelState.AddModelError(
string.Empty,
"Unable to save changes. The field was updated by another user.");
}
}
return RedirectToAction("Edit", new { customerID });
}
}
return View(ViewModelManager.createEditViewModel(model.CustomerID));
}
此外,我在视图中为行版本添加了隐藏字段:
@Html.HiddenFor(model => Model.RowVersion)