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

Hey everyone,

I ran into the following error this morning:

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

It turns out there are a few causes for this. My issue was that I was attempting to open a result set while already iterating over another one.


 //Retrieve list of cart products and create list of suborders
 var cartProducts = db.CartProducts.Where(cartProduct => cartProduct.CartId == userOrder.CartId);

//Loop through each cart product
foreach(var cartProduct in cartProducts)
{
     //Retrieve suborder
     SubOrder subOrder = subOrders.Find(x => x.BusinessId == cartProduct.Product.BusinessId);

The solution to this was pretty easy thankfully. Simply add “ToList()” to the end of the initial request:


 //Retrieve list of cart products and create list of suborders
 var cartProducts = db.CartProducts.Where(cartProduct => cartProduct.CartId == userOrder.CartId).ToList();

An alternative solution is to modify your connection string in order to allow multiple result multiple result sets. Simply add the following to provider part:

MultipleActiveResultSets=true

Checkout these StackOverflow posts for more info:
http://stackoverflow.com/a/10498776/522859
http://stackoverflow.com/a/6064422/522859

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s