Using Statement and Entity Framework

The following code works until I use a commented using statement. When I use using , I get The operation cannot be completed because the DbContext has been disposed

 public IQueryable<DTOs.FormQuestionDTO> GetForm(int id, int page = 0) { // FS stores pages starting with 1 page = page == 0 ? 1 : page; //using (var db = new Models.FormEntities()) //{ var db = new Models.FormEntities(); var questions = from fq in db.FormQuestions join q in db.Questions on fq.QuestionId equals q.QuestionId where (fq.FormId == id) && (fq.PageNumber == page) && fq.Disabled == false orderby fq.DisplayOrder select new { q.QuestionId, q.QuestionText, fq.DisplayOrder, fq.PageNumber }; var dto = questions.Project().To<DTOs.FormQuestionDTO>(); if (questions == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } else { return dto; } //} } 

My initial hunch was that using the DbContext utility right after the LINQ query, but I got the same error when placing .Dipose() inside the finally block.

What's going on here? I haven't been working in C # for a while, so I probably missed something simple.

+1
source share
2 answers

The LINQ Framework Framework provider uses deferred execution . This means that the query is not executed in the database until IQueryable is retried.

What happens when, after your context is configured, something repeats your query, which causes it to try to execute the database query.

You can force it by calling ToList() .

 var dto = questions.Project().To<DTOs.FormQuestionDTO>().ToList(); 
+5
source

+1 ti @jrummell. The reason you get this error is because when a variable declared in using leaves this area, .Dispose () is called on it, which frees DbContext.

If you later try to execute, DbContext no longer exists.

0
source

All Articles