gpt4 book ai didi

c# - EntityFramework 4.5 - 即使在使用 Include 之后仍然会出现 ObjectDisposedException

转载 作者:太空狗 更新时间:2023-10-29 23:22:42 26 4
gpt4 key购买 nike

即使在使用 Include 方法后,我也遇到了异常ObjectContext 实例已被处置并且不能再用于需要连接的操作

这里是检索实体的函数:

    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;

这里是函数的用法:

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

我知道 using 正在关闭连接。我认为 ToList() 将在关闭之前实例化包含的对象列表和相关对象。

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?

谢谢!

最佳答案

尝试改变

    // 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**

引用:http://msdn.microsoft.com/en-us/library/yh598w02.aspx

没有{}为了方便使用,连接被安排在第一行之后。因为 Entity Framework 使用表达式树(这意味着请求在真正需要它之前不会执行),您的查询发生在 var o = (oQuantity[0].EquipmentSection.TypeId);。 .

关于c# - EntityFramework 4.5 - 即使在使用 Include 之后仍然会出现 ObjectDisposedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24457738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com