Asp.net-mvc – Entity Framework: There is already an open DataReader associated with this Command which must be closed first

asp.net-mvcasp.net-mvc-3entity-frameworkentity-framework-4entity-framework-4.1

This question is related to this:

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) ;
        }

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>

The full exception is:

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

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

Best Answer

Quick solution :

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() ;
    }

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.

Related Topic