Return Json from object in C # with Entity Framework

6

I have a problem with returning a Json using Entity Framework. The code I'm using is:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Item(int agendaHorarioID)
{
    using (var db = new ERPContext())
    {
        IList<AgendaHorario> agendaHorario = db.AgendaHorario.Where(w => w.AgendaHorarioID == agendaHorarioID).ToList();
        var teste = agendaHorario.ToArray();
        return Json(new { HttpStatusCode.OK, dados = teste }, JsonRequestBehavior.AllowGet);
    }

}

The error that happens is:

A instância de ObjectContext foi descartada e não pode mais ser usada para operações que exijam uma conexão.

The reason for the problem I know, the object has not been transformed into an array to take away the dependency of the Entity Framework. I've tried in many ways but I could not.

    
asked by anonymous 20.05.2014 / 13:47

3 answers

4

Apparently this problem occurs because of references using lazy loading. Since Dispose() is called because of using , ERPContext ceases to exist. Therefore, when an instance of AgendaHorario is serialized, references to some complex attribute occur, lazy loading is fired and searches for the context that no longer exists.

Instead of sending every object AgendaHorario (which might contain cyclic references), try to select the fields you want to return via JSON and use Include to include the complex properties:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Item(int agendaHorarioID)
{
    using (var db = new ERPContext())
    {
        var dados = db.AgendaHorario.Include(m => m.PropLazy).Where(m => m.AgendaHorarioID == agendaHorarioID).Select(m => new { m.Prop1, m.Prop2 }).ToList();            
        return Json(new { HttpStatusCode.OK, dados }, JsonRequestBehavior.AllowGet);
    }

}
    
20.05.2014 / 17:19
2

If the question is just to get dependency on the Entity Framework, just enumerate the result.

IList<AgendaHorario> agendaHorario = db.AgendaHorario.Where(w => w.AgendaHorarioID == agendaHorarioID).ToList();

EDIT

I do not know your AgendaHorario class, but the [JsonIgnore] attribute avoids loading the properties that are marked with it. When I need to generate a JSON , I use this attribute to avoid generating too much and unnecessary information.

    
20.05.2014 / 17:22
0

You can take two steps to resolve this, one of which is to detach ( detach ) the context object, but this case is recommended when it is an object.

db.Entry(entity).State = EntityState.Detached;

In the case of a list, I would recommend removing% with%

db.AgendaHorario.AsNoTracking().Where(w => w.AgendaHorarioID == agendaHorarioID).ToList();
    
20.05.2014 / 14:18