我尝试保存已编辑的Entity Framework实体ApplyPropertyChanges,并获得异常:
“ObjectStateManager没有 包含带有的ObjectStateEntry 引用类型的对象 'MvcApplication1.Models.Product'。“} System.Exception {System.InvalidOperationException}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product productToEdit) //all properties of Product are valid
{
try
{
productsDBEntities.ApplyPropertyChanges("ProductSet", productToEdit); //exception here
entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
任何想法都会非常感激!
谢谢!
答案 0 :(得分:1)
如果要使用Product
:
ApplyPropertyChanges
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product productToEdit)
{
try
{
entities.Products.Single(p => p.Id == productToEdit.Id);
entities.ApplyPropertyChanges("ProductSet", productToEdit);
entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
或者您可以使用其他方法:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product productToEdit)
{
try
{
entities.AttachTo("ProductSet", productToEdit);
entities.ObjectStateManager.GetObjectStateEntry(productToEdit).SetModified();
entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
顺便说一下。你在使用.NET 3.5吗? {4.0}在.NET 4.0中已经过时了。