将 GridView 绑定到 IQueryable<T> [英] Binding GridView to IQueryable&lt;T&gt;

查看:24
本文介绍了将 GridView 绑定到 IQueryable<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题纯粹是学术性的,因为我从没想过用真实代码来做这个.

This question is purely academic, because I'd never dream of doing this in real code.

使用 LINQ to SQL,我想将 IQueryable 绑定到 GridView.我尝试使用以下代码执行此操作,但出现异常:

Using LINQ to SQL, I want to bind an IQueryable<T> to a GridView. I tried doing this with the following code, but I get the exception:

无法访问已处理的对象.对象名称:'DataContext 在 Dispose 之后访问.'.

Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.

这是我使用 LINQ to SQL 获取 IQueryable 的代码:

Here is my code that gets an IQueryable<tabGenre> using LINQ to SQL:

public static IQueryable<lu_Genre> GetGenres2() {
    using (BooksContextDataContext ctx = new BooksContextDataContext()) {
        IQueryable<tabGenre> iq = from g in ctx.tabGenre
                                  select g;
        return iq;
    }
}

这是我将 GridView 绑定到返回的 IQueryable 的代码.

And here is my code that binds the GridView to the returned IQueryable<T>.

private void GetGenres() {
    gvGenre.DataSource = Genre.GetGenres2();
    gvGenre.DataBind();
}

那么为什么这不起作用?我可以只是一个 .ToList(),返回它,绑定到它然后它就可以工作了,但为什么 IQueryable 不能以同样的方式工作?我真正想在这里实现的是了解 IQueryable 可以做什么.

So why doesn't this work? I could just a .ToList<tabGenre>(), return it, bind to it and then it would work, but why doesn't IQueryable work in the same fashion? What I'm really trying to achieve here is an understanding of what IQueryable can do.

我也尝试禁用延迟加载,但没有影响.

I also tried disabling lazy loading, but to no affect.

推荐答案

您可以将 IQueryable 视为执行查询所需的指令.当您调用 .ToList() 时,您正在执行 IQueryable() 以返回实际数据.当您绑定到 IQueryable() 时,它会期望在调用 DataBind() 时有一个数据源来获取实际数据.

You can think of the IQueryable as the instructions required to execute the query. When you call .ToList(), you are executing the IQueryable() to return actual data. When you bind to IQueryable(), it will expect to have a data source to get the actual data whenever DataBind() is called.

当您设置 gvGenre.DataSource() = Genre.GetGenres2() 时,根据您的 IQueryable 获取实际数据所需的 DataContext 在对 DataBind() 的调用发生之前被销毁.

When you set gvGenre.DataSource() = Genre.GetGenres2(), the DataContext required to get actual data based on your IQueryable is destroyed before the call to DataBind() occurs.

如果您调用 .ToList() ,它会起作用,因为您实际上是出去获取数据,然后将其放入内存.

It works if you call .ToList() because you're physically going out and getting the data, then putting it memory.

存储 IQueryable 就像只存储查询.如果查询期望使用的数据源不存在,则您无法执行查询.

Storing the IQueryable is like storing just the query. You can't execute a query if the datasource it expects to work with doesn't exist.

这篇关于将 GridView 绑定到 IQueryable<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆