Entity framework: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
In the past I have using EF and have encountered with the exception “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection”. At a glance I found the exception very confusing. The ObjectContext is responsible for various task including opening and closing of connection as executing and writing queries.
After some time on internet, the exception can be brought about various reasons
-Attempting to access data whilst the connection has been disposed.
-You are trying to access an entity that is not yet attached to the context.
-Orphaned data, i.e. missing navigation data
-Outdate model especially if you are code database first or model first. You can simply right click on you .edmx file and select update model from Database
The quick fix to this issue is to disable lazy loading via the DbContext constructor
This flag is usuallly set to true by default, setting it false disables lazy loading even if proxies is created. There are two type of dynamic proxies created in EF
- Proxies for lazy loading
- Proxies for change tracking
Usually a change tracking proxy also can serve as a proxy for lazy loading. The reverse is not true. This is because the requirements for change tracking proxies are higher, especially all properties – also the scalar properties – must be virtual. For lazy loading it is enough that the navigation properties are virtual.
If you want to completely disable change tracking and lazy loading creation proxies use the
More on proxies in future