开发者

binding gridview with my getall method - entity framework

Ok please excuse my references to the gridview.

So I have this method in a class called getall() what this does is gets the collection of entites f开发者_如何学JAVArom entity framework model for a specfic table, checks to see whether the table exists and then does the query using linq (linq to entities). This does work as I have used a breakpoint and even created a seperate test project in order to test it. However when binding it with a gridview has proven difficult for me.

This is the code I used:

protected void Button2_Click(object sender, EventArgs e)

    {
        dCollection d = new dCollection();

        GridView1.DataSource = d.GetAll();
        GridView1.DataBind();
    }

However I get an error saying:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 

I'm using a collection to get all my methods from the class dcollection and one of my methods is getall, which will get all records from the table. Why does this not work?


This error comes from the fact that you have bindings to some navigation properties inside your GridView that has NOT been loaded yet. Therefore when you call the DataBind() it tries to "Lazy Load" those navigation properties and as this happens outside of your ObjectContext living scope (i.e. it has been already disposed) you'll get this error.

The solution is to either "Eager Load" all of the nav properties that your GridView is using or disable Lazy Loading on your object context.

In your case, I would suggest to always disable Lazy Loading regardless of whether or not you eager load the nav properties since it's a good practice for Web applications like this to always disable Lazy Loading. Once it is disabled, you can still explicitly load related data on demand if needed, or eager load them with the initial query.

This post contains a more detailed discussion on this issue as well as how you can disable Lazy Loading.

By the way, the reason your Test Project works is becasue you do not access those "not loaded" nav properties in there, therefore LazyLoading does not happens.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜