I have several action methods that return a json object. e.g:
public JsonResult MyAction()
{
var entities = db.Entities.Include("Location").Where(e => e.Name != null);
var model = entities.Select(e => new MyModel(e));
return Json(model, JsonRequestBehavior.AllowGet);
}
In some of the model classes I access inner elements of the entities e.g.
public class MyModel
{
private Entity _e;
public MyModel(Entity e)
{
_e = e;
}
public string[] LocationName
{
get
{
return _e.Location.Name;
}
}
}
This works just fine if I the repository (db) in a place like the OnRequestCompleted in the Global.asax.cs file. The problem is that right now I'm disposing the db in the OnActionExecuted method of the BaseController, and when the object is being serialized it fails bc the connection is already closed.
My question is, is OnActionExecuted the correct place to dispose the database connection or should I execute it somewhere else? If it is ok to dispose the repository there, then how can I "force" the serialization to take place the moment I call Json(model) so it won't fail afterwards.
Thanks for your help!