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

DbContext.Configuration.LazyLoadingEnabled

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

DbContext.Configuration.ProxyCreationEnabled

More on proxies in future

Share this:

Like this:

When working with even the latest version of ASP NET MVC 4, there are times when you will need to return Json from you controllers. In this case the framework utilizes the JavascriptSerializer. This is the default for ASP NET MVC unlike the ASP NET WEB API which uses Json.Net

Also worthy noting is that JsonValueProviderFactory uses the JavascriptSerializer to deserialize request body to action parameters. My problems with JavascriptSerializer on ASP NET MVC as follows:

1. The date format that is returned: Most of the times I have come across this date format ( Date(1365850930898)).

2. Circular reference which is a common issue when working with Entity framework. Though there are work around for this like disable lazy loading, its not an ideal solution as lazy loading is one for main reason for the ORM like EF.

To solve all these related issue, JSON.NET comes into play as it has solution to these issues. Actually JSON.NET is the default json serializer for ASP NET WEB API.

Without further ado, I will go straight to explain how to go about these issues:

The first step is to implement our own custom json serializer which extends the JsonResult class