January 26, 2015 |

Today I ran into an issue with related databases in a C# web application that I am working on. The application accesses SQL Server database tables using the .NET Entity Framework version 6. The error read:

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

I had a service object storing a list of results from one table, but the error was thrown when my code in another part of the application tried to access the related items (as designated by the entity framework). When diagnosing the error, I recalled reading about lazy loading in the entity framework set up. Overall lazy loading helps lower the amount of system resources needed since related items are not loaded until needed. Unfortunately, in this instance, it was preventing the web app from accessing those resources due to where and when the original list was being created.

To resolve the error, Stack Overflow came through with a solution to a similar need that would work for this issue. Here is the C# code I was using that was throwing the error:

var result = from item in db.Table1
             where item.Term == term
             select item;
return result.ToList();

And here is the update code after I added the Include(). Note that Table2Navigation is the name given to the navigation property in Table1 relating it to Table2.

var result = from item in db.Table1
             where item.Term == term
             select item;
return result.Include(i => i.Table2Navigation).ToList();

Once that change was made, my C# web application ran successfully, eliminating the pesky error.

Posted in: , ,


Comments are disabled