Your expectation and your current execution are contradicting one another.
I'd like to use lazy loading in my application
The ObjectContext instance has been disposed and can no longer be used
The error message clearly reveals that you are still expecting to access data (via lazy loading) after you've closed your context, which is impossible.
There are two solutions here:
1. Ensure you don't close your context until you're done lazily loading data.
This is how you're suppose to do lazy loading, by design. Assuming you're using a using
statement, ensure that you only fetch data while inside the using
block.
However, you will notice that in large codebases, it becomes hard to ensure that the context is kept open long enough. Which I why I urge you to consider the other option:
2. Switch to eager loading.
Lazy loading is a very simple approach and works well enough in tiny applications (e.g. when I write a short-term-usage tool to help me). However, for larger infrastructures, lazy loading starts leading to mistakes that are easy to make but painfully hard to debug.
While eager loading doesn't avoid these runtime exceptions, the exceptions you will encounter (having forgotten an Include
statement) will be much easier to debug, compared to having to figure out which data was being lazily loaded at what point.
I'm not going to tell you you can't use lazy loading, but you do need to be aware of the complexities that this leads to. For sufficiently large codebases, it becomes nigh unmaintainable to keep track of whether you closed the context too soon or not.
The cost of maintaining this (and debugging all the issues that you didn't prevent) is going to vastly outweigh the slightly more verbose code required for eager loading.