0

这个问题已经被问过很多次了,但我仍然不明白为什么我一直收到这个错误。

在我的控制器中,我有这个方法:

//
// POST : /ObjectProducer/Edit/5
[HttpPost]
public ActionResult Edit(OBJECT_PRODUCER _objProd)
{
    if (ModelState.IsValid)
    {
        m_Db.Entry(_objProd).State = EntityState.Modified;
        m_Db.SaveChanges();
        return RedirectToAction("SearchIndex");
    }

    return View(_objProd);
}

但是当我打m_Db.Entry(_objProd).State = EntityState.Modified;线时,就会发生错误。谁能向我解释有什么问题?

** 编辑 **

这是启动“编辑”方法的控制器方法(“GET”方法)

//
// GET : /PriceProvider/Edit
public ActionResult Edit(int id = 0)
{
    OBJECT_PRODUCER objProd = m_ProductManager.GetObjProdByID(id);

    if (objProd == null)
    {
        ViewData["ErrorMessage"] = m_NoDataFound;
    }

    return View(objProd);
}
4

2 回答 2

3

我认为您需要执行几个步骤,这应该可以解决您的问题:

  1. 在从用户提交时,您需要从用户正在编辑的 dbContext 中获取实体。
  2. 然后根据用户提交的实体从 dbContext 更新实体上的值。

我正在使用 Entity Framework 5,这是我用来根据用户提交的更新实体更新原始实体的代码:

public virtual void Update(TEntity entityToUpdate, TEntity originalEntity)
    {
        ctx.Entry(originalEntity).CurrentValues.SetValues(entityToUpdate);
    }

所以我认为在你的情况下:

public ActionResult Edit(OBJECT_PRODUCER _objProd)
{
    if (ModelState.IsValid)
    {
        //this line might not be quite right, but basically 
        //get the entity from dbContext based on the id of the submitted object
        OBJECT_PRODUCER originalFromDbContext = m_Db.GetById(_objProd.Id);

        //set the values for the Entity retrieved from m_Db to the new values
        //submitted by the user
        m_Db.Entry(originalFromDbContext).CurrentValues.SetValues(_objProd);

        m_Db.SaveChanges(); //save changes
        return RedirectToAction("SearchIndex");
    }
    return View(_objProd);
}
于 2013-04-05T18:17:07.880 回答
1

尝试从 m_Db 重新获取 _objProd 实体。您在帖子中获得的内容实际上并不是您当前数据上下文的一部分,它来自编辑的获取版本中使用的数据上下文。

var _newObjProd = m_Db.GetObjProdByID(_objProd.ID);

基本上,实体在两个 DataContext 中表现不佳。您需要在新的数据上下文中再次加载实体。

于 2013-04-05T17:01:09.770 回答