1
我目前按照本教程DbUpdateConcurrencyException不存在的
不過,我似乎無法得到發生併發異常(DbUpdateConcurrencyException)。
我在相關表格中創建了一個Timestamp字段(在我的項目中稱爲'Group')。
我的代碼在GroupController.cs如下
[HttpPost]
public ActionResult Edit(Group group)
{
try
{
if (ModelState.IsValid)
{
medEntitiesDB.Entry(group).State = EntityState.Modified;
medEntitiesDB.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValues = (Group)entry.GetDatabaseValues().ToObject();
var clientValues = (Group)entry.Entity;
if (databaseValues.GroupName != clientValues.GroupName)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.GroupName);
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.");
group.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(group);
}
我的 '集團' 類是如下
namespace MyClasses
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
public partial class Group
{
public System.Guid GroupID { get; set; }
public string GroupName { get; set; }
public System.DateTime DateCreated { get; set; }
[Timestamp]
public byte[] Timestamp { get; set; }
}
}
有誰知道爲什麼這個異常沒有發生?
您可能沒有正確地按照教程進行操作,並且錯過了一些步驟,例如在表單中包含'Timestap'作爲隱藏字段。 –
@ Html.HiddenFor(model => model.Timestamp)已包含在我的'編輯'視圖中,所以它必須是別的。 – jjc99
是的,它一定是別的東西,因爲文章中的代碼工作正常。 –