我在我的action方法中为DbUpdateConcurrencyException
定义了一个catch语句,我在我的数据库和模型类中包含了一个timestamp列。我设置了concurrency = Fixed
。但如果两个用户试图编辑同一个对象,则不会引发DbUpdateConcurrencyException
!
以下是代码:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Class c = repository.GetClass(id);
try
{
if (TryUpdateModel(c))
{
epository.Save();
return RedirectToAction("Details", new { id = c.ClassID });
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValues = (Class)entry.GetDatabaseValues().ToObject();
var clientValues = (Class)entry.Entity;
if (databaseValues.ClassName != clientValues.ClassName)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.ClassName);
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.");
c.Timestamp = databaseValues.Timestamp;
}
catch (DataException)
{
//Log the error (add a variable name after Exception)
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
return View(c);
}