1

我想将最后搜索的查询保存在全局变量中,当我在另一种方法中使用它时,它会说:

用户代码未处理 ObjectDisposedException:ObjectContext 实例已被释放,不能再用于需要连接的操作。

IQueryable lastQry = null;

private void SearchMethod()
{
   using(var ctx = new entityContex())
   {
      var qry = ctx.Table1.Where(t=> t.Name.StartWith(txtName.Text)).Take(100);

      lastQry = qry;

      dgvResult.DataSource = qry.ToList();
   }
}

private void RefreshResult()
{
   using(var ctx = new entityContex())
   {
      if(lastQry != null)
      //here is the Error ! <<---------------->>
      dgvResult.DataSource = lastQry.ToList();
   }
}
4

2 回答 2

1

一种方法是创建并存储一个运行查询的委托:

Func<entityContex, IQueryable</*Table1 type*/>> queryExecutor = null;

private void SearchMethod()
{
   using(var ctx = new entityContex())
   {
      queryExecutor = c => c.Table1.Where(t=> t.Name.StartWith(txtName.Text)).Take(100);

      var qry = queryExecutor(ctx);

      dgvResult.DataSource = qry.ToList();
   }
}

private void RefreshResult()
{
   using(var ctx = new entityContex())
   {
      if(queryExecutor != null)
      dgvResult.DataSource = queryExecutor(ctx).ToList();
   }
}
于 2013-08-16T11:14:17.943 回答
0

与其存储 ,不如存储IQueryable列表:

List<Table1> lastQry = null;

private void SearchMethod()
{
 using(var ctx = new entityContex())
 {
   var qry = 
     ctx.Table1
       .Where(t=> t.Name.StartWith(txtName.Text))
       .Take(100)
       .ToList(); // <--

   lastQry = qry;
   dgvResult.DataSource = qry;
 }
}

private void RefreshResult()
{
  using(var ctx = new entityContex())
  {
    if(lastQry != null)
      dgvResult.DataSource = lastQry;
  }
}
于 2013-08-14T06:29:13.720 回答