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

When your MVC 5 web application page tries to read the database using the Entity Framework in a loop you may get the following error message:

InnerException: System.InvalidOperationException
HResult=-2146233079
Message=There is already an open DataReader associated with this Command which must be closed first.
Source=System.Data

This usually happens when a cshtml page receives an IEnumerable<> model from the database and makes repeated calls to retrieve the rows one-by-one in a foreach loop.

If your page does not display paged data, read the rows into a List  with the ToList() method and send the list to the cshtml page to iterate through it. This forces the application to read all appropriate rows with one call from the database.

Sometimes you can also eliminate the problem if you add the following to the connection string in the web.config file:

;multipleactiveresultsets=True

Leave a comment

Your email address will not be published. Required fields are marked *