I am facing the exception The ObjectContext instance has been disposed and can no longer be used for operations that require a connection even after using the Include method.
Here the function that retrieve the 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
where Header.Formula == strFormula
&& Header.VersionId == iVersionId
select Grid).ToList();
// return
return oList;
Here the usage of the function:
// retrieve ingredient quantity by equipement
using (Model.CapacityGrid oModel = new Model.CapacityGrid(Configuration.RemoteDatabase))
oQuantity = oModel.SelectByFormula(strFormulaName, iVersionId);
// code to throw the exception
var o = (oQuantity[0].EquipmentSection.TypeId);
I understand that the using is closing the connection. I thought the ToList() will instantiated the list of objects and the related objects in the include before closing.
Can someone point me out what I do wrong? Sorry, my question was not clear. I do understand that including the line that throw exception inside the bracket of the using is working, but I do not figure out why does the include does not works?
Thank you!
Try changing
// retrieve ingredient quantity by equipement
using (Model.CapacityGrid oModel = new Model.CapacityGrid(Configuration.RemoteDatabase))
{ // <-- **add these**
oQuantity = oModel.SelectByFormula(strFormulaName, iVersionId);
// code to throw the exception
var o = (oQuantity[0].EquipmentSection.TypeId);
} // <-- **add these**
Ref: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
With no {}
to englobe the using, the connection is disposed right after the first line. Because Entity framework uses Expression trees (this means that the request is not executed until it really needs it), your query happens at var o = (oQuantity[0].EquipmentSection.TypeId);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With