使用语句和实体框架 [英] Using Statement and Entity Framework
问题描述
以下代码只要不使用已注释掉的使用
语句即可。当我使用使用
我得到操作无法完成,因为DbContext已被处理
The following code works as long as I don't use the commented out 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;
}
//}
}
在使用LINQ查询后,使用正在处理 DbContext
,但是当放入 .Dipose()
$ code>最终块
My original hunch was that Using is disposing of the DbContext
right after the LINQ query but I got the same error when putting the .Dipose()
inside of a finally
block.
这里发生了什么?我没有在C#中工作一段时间,所以我可能会丢失一些简单的东西。
What's going on here? I haven't worked in C# for a while so I'm probably missing something simple.
推荐答案
实体框架LINQ提供者使用延期执行。这意味着在IQueryable被迭代之前,该查询不会在数据库上执行。
The Entity Framework LINQ provider uses deferred execution. This means that the query is not executed on the database until the IQueryable is iterated.
发生的情况是,在你的上下文被处理之后,有些事情会迭代你的可查询,这导致它尝试执行数据库查询。
What's happening is that after your context is disposed, something iterates your queryable which causes it to try to execute the database query.
您可以通过调用 ToList()
来强制执行。
You can force it to execute immediately by calling ToList()
.
var dto = questions.Project().To<DTOs.FormQuestionDTO>().ToList();
这篇关于使用语句和实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!