Oct 3, 2012

Asp.Net MVC Web Api and Entity Framework issues (and the resolution)

Recently, I was working on a test project for Asp.Net Web Api. The models were auto-generated EF models (DB first).
The dummy database is that of a School. So the Tables/Classes are   Standard, Section, Students, Teachers
Relationship:
Standard: Section = 1:1
Standard: Student = 1 : many
So in my StandardController, I have 2 methods:
Get – returns back all the Standards
and
Get(int id) – returns back the individual Standard based on the passed id

They return back json objects which is parsed by a jquery function in a view and a html table is created based on the content.

The calls were all reaching the Controller and then the classes were also properly fetched from the Db and returned.. but the jsnon was always erroring out..

Even after repeated attempts there was failure in retrieving the data.

I inspected the response object through Mozilla's firebug plugin and saw that it contained a JSON serialization exception.


I was using a “using” block to fetch the entities thru LINQ / lambda and then populating a local variable which was returned back to the view..

The Controller code before the change..

public Enumerable<Standard> Get()
{  IEnumerable Standards= null;  string connstr = SessionFactory.DBConnectionString;
 SchoolEntities context = new SchoolEntities (connection); /// the data context
  using (EntityConnection connection = new EntityConnection(connstr)) {

  using (SchoolEntities context = new SchoolEntities(connection))
  {
    context.ContextOptions.LazyLoadingEnabled = true;
    Standards = context.Standards;
  });
}
}

return Standards;
}

I searched the net and found that the problem was in fetching and then retaining the inner collection of Students contained within each of the Standard object.

After trying multiple ways to mitigate it, I tried one thing which worked

I just had to remove the using section and was manually opening and closing the  data context and entity connection
And it worked!!!

The changed code:

public Enumerable<Standard> Get()
{

IEnumerable Standards = null;

string connstr = SessionFactory.DBConnectionString;

EntityConnection connection = new EntityConnection(connstr);
connection.Open(); // Open the connection
 

SchoolEntities context = new SchoolEntities (connection); /// the data context

Standards= context.Standards;

connection.Close();
return standards;

}