通过MVC中的ApplyPropertyChanges将更改应用于EF模型时出现异常

时间:2011-04-26 22:13:29

标签: asp.net-mvc entity-framework edit

我尝试保存已编辑的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();
                }
            }

任何想法都会非常感激!

谢谢!

1 个答案:

答案 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中已经过时了。