0

I found this code here

   using (var objCtx = new SchoolDBEntities())
{
    var schoolCourse = from cs in objCtx.Courses
                       where cs.CourseName == "Course1"
                       select cs;
    Course mathCourse = schoolCourse.FirstOrDefault<Course>();
    IList<Course> courseList = schoolCourse.ToList<Course>();

    string courseName = mathCourse.CourseName;
}

And I am using it in a Get method of a web api. When i use a using statement I get the following error The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

I I do not use it, then how would I dispose of the context object responsibly?

Jude Fisher
  • 11,138
  • 7
  • 48
  • 91
Nick
  • 841
  • 2
  • 9
  • 30
  • 1
    This might be handy : http://stackoverflow.com/questions/18398356/how-to-solve-the-error-the-objectcontext-instance-has-been-disposed-and-can-no-l Can you post your EF classes, if you're using Plain Old Clr Objects (POCO)? – Jason Evans Jan 30 '14 at 13:48

1 Answers1

1

I use something like this to solve the problem without resorting to eager loading (in fact usually in a generic abstract base controller that I extend, but this example is simplified):

public class MyController : ApiController
{
    private SchoolDBEntities _objCtx;

    // Singleton ObjectContext
    protected SchoolDBEntities objCtx
    {
        if(_objCtx == null) _objCtx = new SchoolDBEntities();
        return _objCtx;
    }

    // Use singleton objCtx without using wrapper here, in Get() or other methods.
    public String Get()
    {
        var schoolCourse = from cs in objCtx.Courses
                   where cs.CourseName == "Course1"
                   select cs;
        Course mathCourse = schoolCourse.FirstOrDefault<Course>();
        string courseName = mathCourse.CourseName;
        return courseName
    }

    // ApiController implements IDisposable, so you can override Dispose to do clean-up here.
    // This is not called until the controller is disposed, so you won't get the error you report.
    protected override void Dispose(Boolean disposing)
    {
        if (_objCtx!= null)
        {
            _objCtx.Dispose();
            _objCtx = null;
        }
        base.Dispose(disposing);
    }

}
Jude Fisher
  • 11,138
  • 7
  • 48
  • 91