实体框架:已经有一个用此命令,必须先关闭相关联的打开的DataReader [英] Entity Framework: There is already an open DataReader associated with this Command which must be closed first

查看:131
本文介绍了实体框架:已经有一个用此命令,必须先关闭相关联的打开的DataReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是关系到<一个href=\"http://stackoverflow.com/questions/7917261/how-to-load-the-related-entities-using-entity-framework-and-the-repository-patte\">this:

我的库法有此code:

My repository method has this code:

 public IEnumerable<ApplicationPositionHistory> GetApplicationPositionHistories(int applicantId, int positionId)
        {
            return context.ApplicationsPositionHistory.Where(d => d.applicantPosition.ApplicantID == applicantId && d.applicantPosition.PositionID == positionId).Include(o => o.applicantPosition) ;
        }

我的HTML有这个code:

My Html has this code:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.applicantPosition.Applicant.name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.applicantPosition.Position.name)
        </td>

完整的例外是:

有已经使用此命令,必须先关闭相关联的打开的DataReader。

There is already an open DataReader associated with this Command which must be closed first.

这是掷在HTML的第一行
  @ Html.DisplayFor(modelItem => item.applicantPosition.Applicant.name)

It was throw in the first line of the HTML @Html.DisplayFor(modelItem => item.applicantPosition.Applicant.name)

推荐答案

快速的解决方案:

public IEnumerable<ApplicationPositionHistory> GetApplicationPositionHistories(int applicantId, int positionId)
    {
        return context.ApplicationsPositionHistory.Where(d => d.applicantPosition.ApplicantID == applicantId && d.applicantPosition.PositionID == positionId).Include(o => o.applicantPosition).ToList() ;
    }

如果你想知道,为什么这个修复您的问题,了解如何LINQ和递延执行的作品。在几句话 - 如果你不通过了ToList枚举查询选择的力的执行,它其实是在执行为时已晚 - 在视图中。这也是造成麻烦,而要使用相同的连接其他查询。

If you want to know, why this fixing your problem, read about how LINQ and deffered execution works. In few words - if you dont "force" execution of the select by "enumerating" query by ToList, it is in fact executed too late - in view. And this is causing trouble with other queries which want to use same connection.

这篇关于实体框架:已经有一个用此命令,必须先关闭相关联的打开的DataReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆