c# - EntityFramework 4.5 - Still get ObjectDisposedException even after using Include -
i facing exception the objectcontext instance has been disposed , can no longer used operations require connection after using include method.
here function retrieve entities:
public list<entity.capacitygrid> selectbyformula(string strformula, int iversionid) { // declaration list<entity.capacitygrid> olist; // retrieve ingredients olist = (from grid in _dc.capacitygrid.include("equipmentsection") join header in _dc.capacityheader on grid.headerid equals header.headerid header.formula == strformula && header.versionid == iversionid select grid).tolist(); // return return olist;
here usage of function:
// retrieve ingredient quantity equipement using (model.capacitygrid omodel = new model.capacitygrid(configuration.remotedatabase)) oquantity = omodel.selectbyformula(strformulaname, iversionid); // code throw exception var o = (oquantity[0].equipmentsection.typeid);
i understand using closing connection. thought tolist() instantiated list of objects , related objects in include before closing.
can point me out wrong? sorry, question not clear. understand including line throw exception inside bracket of using working, not figure out why include not works?
thank you!
there 3 solutions problem. these come link here , 3 ways link related entity. first solution lazy loading solution, have been using. modify code , work. reason why throwing exception because lazy loading occurs when need it. it's great solution when need load related entities on few entities.
// retrieve ingredient quantity equipement using (model.capacitygrid omodel = new model.capacitygrid(configuration.remotedatabase)) { oquantity = omodel.selectbyformula(strformulaname, iversionid); // lazy-load occurs here, needs have access // context, hence why in using statement. var o = (oquantity.first().equipmentsection.typeid); }
the second solution use eager-loading (as suggested @davidg). because load related entity of first entity found, not recommend use in case because load equipmentsection entity of oquantity entities. in selectbyformula
method, use include statement shown in related link , load on first call (it not duplicate access database, pull more data @ once).
the third solution avoid relying on lazy loading, , can way go to. it's explicit loading technique, require specify want load equipmentsection
related entity on specified entity.
i hope explanations you.
also, might want consider returning iqueryable on selectbyformula
method. way, if have filter requests, first()
method obtain first occurance, not pulling 1 instance.
Comments
Post a Comment