2

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!

1 Answer 1

1

I think the real problem is that you are returning an IQueryable, which requires the connection.

It's always better to decide when exactly you want the query to be executed, at least to prevent multiple executions for example.

If you force the execution, you already have the result, and you can dispose the DB no problem.

Example:

public JsonResult MyAction()
{
  var entities = db.Entities.Include("Location").Where(e => e.Name != null);
  var model = entities.Select(e => new MyModel(e))
                      .ToList(); // Execute IQueryable to get List<MyModel>
  return Json(model, JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Actually that's not exactly true, even if I use the ToList() it will only get the Entities, but not the Locations. The locations will be retrieved when they are accessed, which in this case is when the serialization occurs.
Well, this means the eager loading is not working and they're still treated as lazy loaded property, which is sort of a different issue. Did you try to take off the the entity from your model and just have a property assigned in your select lambda?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.