2

I use asp.net mvc5 with EF, in this few string i received "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection". What's wrong?

public JsonResult GetResponibleParty()
{
    List<CI_ResponsibleParty> resParty;
    using (MetabaseDbContext context = new MetabaseDbContext())
    {
        resParty = context.SetOfResponsibleParty.ToList();
        return Json(resParty, JsonRequestBehavior.AllowGet);
    }       
}
Andrey
  • 21
  • 3
  • can you show what `CI_ResponsibleParty` contains? Could be that it has some refferences, that doesn't load with `ToList()`, but they need after. So it's really better to create `ResponsiblePartyViewModel` that has only properties that you need this will definatly solve your problem. – teo van kot Jul 17 '15 at 10:02
  • Where this error is shown? Could you show whole class? – kamil-mrzyglod Jul 17 '15 at 12:11
  • teo van kot: yes, you are right. Trouble was in LazyLoading process. – Andrey Jul 17 '15 at 12:23
  • Turn lazy loading off, add/or `.AsNoTracking()` just before you do `.ToList()`. – trailmax Jul 17 '15 at 12:35

2 Answers2

1

Move your return statement after the using block. You have already created a list and held it in a variable.

public JsonResult GetResponibleParty()
{
    List<CI_ResponsibleParty> resParty;
    using (MetabaseDbContext context = new MetabaseDbContext())
    {
        resParty = context.SetOfResponsibleParty.ToList();
    }       
    return Json(resParty, JsonRequestBehavior.AllowGet);
}
Oliver Gray
  • 874
  • 6
  • 17
0

Solution found. In this case me helped 2 methods:

1) context.Configuration.LazyLoadingEnabled = false;
2) or using .Include()
Andrey
  • 21
  • 3
  • 1
    The solution to this problem is to return view models instead of Entity Framework models. – Sergey Akopov Jul 17 '15 at 12:34
  • But in this controller's method me need return Json – Andrey Jul 17 '15 at 12:49
  • 1
    What you ultimately need to do is return a simple object that you can map your EF model to and return that instead of your EF model. This object is often called the View Model or a DTO (Data Transfer Object). You never want to either accept or return database model objects in your controller actions. – Sergey Akopov Jul 17 '15 at 21:11
  • The DTO / ViewModel has fixed my problem, I can't believe I missed this! – Clyde Jan 05 '21 at 14:23