How to Get Linq to Prepopulate/Explicitly Fetch Data From the Database

Several people have commented to me on using LINQ to SQL and getting an ObjectDisposedException message when trying to access the returned data.

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

This can occur when using Linq to SQL to retrieve data from a database – and when you try to access data after the DataContext object has been disposed.  More specifically, the exception occurs when trying to access an item that has not yet been retrieved from the database and the DataContext object has been disposed.
 
This often happens after a Using() block

using(…datacontext)

This works fine when accessing data explicitly retrieved within the Using() block – but the exception occurs when you try to access other items that were not retrieved.

The solution is to force the DataContext to return all the data immediately. We can use one of the GetEnumerator functions, such as ToList(). This forces all the data to return before the DataContext is released.

 

// holds the list of results
List<MySprocResults> ResultList = null;

// connect to the database, wrapping everything in a using statement
using (MyDBDataContext MyDB = new MyDBDataContext())
{
    // get the results from the database
    ResultList = MyDB.MySprocResults().ToList();
}

// we can now use the data in ResultList with no problems
Console.WriteLine(ResultList[0]);

 

If you have any questions, comments, or suggestions, please feel to post them in the LINQ Exchange Forum

GD Star Rating
loading...
GD Star Rating
loading...
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply