简体   繁体   中英

The operation cannot be completed because the DbContext has been disposed

This question has already been asked many times, but I still don't understand why I keep getting this error.

In my controller I have this method:

//
// 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);
}

But when I hit the m_Db.Entry(_objProd).State = EntityState.Modified; line, the error occurs. Can anyone explain to me what's wrong?

** EDIT **

Here's the controller method which initiates the "Edit" method (The "GET" method)

//
// 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);
}

I think you need to follow a couple steps and this should solve your problem:

  1. On submit from user, you need to get the Entity from the dbContext that the user is editing.
  2. Then update the values on the Entity from the dbContext based on the Entity the user submitted.

I'm using Entity Framework 5, and this is the code I use to update the original entity based on the updated entity the user submitted:

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

So I think in your case:

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);
}

Try re-fetching the _objProd entity from m_Db. The one you get in your post isn't actually part of your current datacontext, it is from the datacontext used in the Get version of Edit.

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

Basically entities don't play nice across two DataContexts. You need to load the entity again in the new datacontext.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM