views:

28

answers:

1

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 from 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. Am 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?

A: 

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.

Morteza Manavi
NOPE SORRY, YOU ARE RIGHT. Thank you :)
Sharepoint
You are welcome.
Morteza Manavi