Archive | April 2013

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

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

Using Json.NET to implement your own json serializer (ASP NET MVC)

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

public class CustomJsonResult : JsonResult
{
public CustomJsonResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}

public JsonSerializerSettings Settings { get; set; }

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");

if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("Json get is not supported");

var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;

if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;

if (Data == null)
return;

var scriptSerializer = Newtonsoft.Json.JsonSerializer.Create(Settings);

using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, Data);
response.Write(sw.ToString());
}

}
}

And since i write working with base controller where I can share all common functionality I have implemented a base controller as follows

<pre>public class BaseController : Controller
{
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
//Lets return our new custom result
return new CustomJsonResult
{
Data = data,
ContentEncoding = contentEncoding,
ContentType = contentType,
};
}
}</pre>

Here is my home controller which first first uses the JsonResult

<pre>public JsonResult Products()
{
return new JsonResult
{
Data = DummyOrders(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}</pre>

jsonresult

So to test my custom serializer I charged the action as follows

<pre>        //Action to test our new custom result
public CustomJsonResult Products()
{
return new CustomJsonResult
{
Data = DummyOrders(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Settings =
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
}
};
}</pre>

And here is the result

customjsonresult

 

 

 

 

 

So comparing the two result you can actually look at the date returned.

Kind reading and let me know you thougts

 

Download code from  here

Ola Nerdimingos

Watch this space for information on new and cool stuff on .net framework stack!!!

Keep watching!!

%d bloggers like this: