【发布时间】:2014-06-27 17:35:40
【问题描述】:
我正面临异常ObjectContext 实例已被释放,即使在使用 Include 方法后也无法再用于需要连接的操作。
这里是检索实体的函数:
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);
我知道使用正在关闭连接。我认为 ToList() 将在关闭之前实例化包含中的对象列表和相关对象。
谁能指出我做错了什么? 抱歉,我的问题不清楚。我确实知道在 using 的括号内包含引发异常的行是有效的,但我不明白 为什么包含不起作用?
谢谢!
【问题讨论】:
-
在
ToList之前尝试.Include,如下所示:.Include(g => g.Equipmentsection).ToList() -
你好 DavidG,不知何故,没有包含函数。我写了这行代码并收到消息:System.Linq.IQueryable
' 不包含“包含”的定义,并且没有扩展方法“包含”接受类型的第一个参数。谢谢! -
我假设
_Dc.CapacityGrid是DbSet?如果是这样,那么 Include 确实应该起作用。你检查生成的 SQL 了吗? -
@SebastienDErrico:您是否包含了 System.Data.Entity 命名空间?这是设置
Include扩展方法的地方。 -
你说得对,我错过了对 System.Data.Entity 的使用
标签: c# entity-framework