我想将最后搜索到的查询保存在全局变量中,当我在另一种方法中使用它时,它会说:
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();
}
}
答案 0 :(得分: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();
}
}
答案 1 :(得分: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;
}
}