在ActionResult Edit中,我有以下代码:
public ActionResult Edit(Product product)
{
try
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch(DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValuesObj = entry.GetDatabaseValues().ToObject();
var databaseValues = (Product)databaseValuesObj;
var clientValues = (Product)entry.Entity;
if (databaseValues.Name != clientValues.Name)
ModelState.AddModelError("Name", "Current value: "
+ databaseValues.Name);
if (databaseValues.Description != clientValues.Description)
ModelState.AddModelError("Description", "Current value: "
+ String.Format("{0:c}", databaseValues.Description));
if (databaseValues.ControllingStudentId != clientValues.ControllingStudentId)
ModelState.AddModelError("ControllingStudentId", "Current value: "
+ String.Format("{0:d}", databaseValues.ControllingStudentId));
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.");
product.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(product);
}
在var databaseValuesObj = entry.GetDatabaseValues().ToObject();
行,我得到一个像这样的例外:
System.Data.EntitySqlException was unhandled by user code
Message=Type 'MvcApplication3.DAL.Product' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly. Near type name, line 1, column 119.
Source=System.Data.Entity
Column=119
ErrorContext=type name, line 1, column 119
ErrorDescription=Type 'MvcApplication3.DAL.Product' could not be found. Make sure that the required schemas are loaded and that the namespaces are imported correctly.
Line=1
...
我的问题是,如何在Product类的哪个位置显示它?它在项目中,我在顶部有使用声明。为什么不能找到它?
编辑: 根据以下回复,我将代码更改为:
var entry = ex.Entries.Single();
var currentValues = entry.CurrentValues.Clone();
entry.Reload();
entry.CurrentValues.SetValues(currentValues);
var clientValues = (Product)entry.Entity;
var databaseValues = (Product)entry.OriginalValues.ToObject();
这似乎解决了这个问题。但我认为如果删除该行会有问题。我目前的问题不会出现这个问题,所以对我来说这是一个很好的解决方案。谢谢!
答案 0 :(得分:1)
当上下文位于不同的项目中时,这是一个已知问题。除了将上下文移动到同一个项目之外,目前还没有解决方法。
修改的 实际上我把它拿回来 - 自从我上次读这篇文章以来,现在有一个解决方法。很酷:)