c# - The operation cannot be completed because the DbContext has been disposed -


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

in controller have 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 hit m_db.entry(_objprod).state = entitystate.modified; line, error occurs. can explain me what's wrong?

** edit **

here's controller method initiates "edit" method (the "get" method)

// // : /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 need follow couple steps , should solve problem:

  1. on submit user, need entity dbcontext user editing.
  2. then update values on entity dbcontext based on entity user submitted.

i'm using entity framework 5, , code use update original entity based on updated entity user submitted:

public virtual void update(tentity entitytoupdate, tentity originalentity)     {         ctx.entry(originalentity).currentvalues.setvalues(entitytoupdate);     } 

so think in case:

public actionresult edit(object_producer _objprod) {     if (modelstate.isvalid)     {         //this line might not quite right,          //get entity dbcontext based on id of submitted object         object_producer originalfromdbcontext = m_db.getbyid(_objprod.id);          //set values entity retrieved m_db new values         //submitted user         m_db.entry(originalfromdbcontext).currentvalues.setvalues(_objprod);          m_db.savechanges(); //save changes         return redirecttoaction("searchindex");     }     return view(_objprod); } 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -