While running a load test on one of our QA environment sites, we noticed that the site went down, adding three warnings to the event log.
The first was an InvalidOperationException with message: There is already an open DataReader associated with this Command which must be closed first.
About a minute later, the second one happened, an InvalidCastException with message: Unable to cast object of type ‘System.Int32′ to type ‘System.String’.
Another minute later and we got this one, an InvalidCastException with message: Specified cast is not valid.
We thought the second one’s message was rather weird because how can you get an invalid cast exception trying to cast an int to a string?! So we Googled it, as well as the DataReader error message, and found many cases, all pointing to Linq’s DataContext as being the culprit. It seems as though, under relatively high load, the DataContext does not get disposed of automatically as you would assume it would. Setting multipleactiveresultsets (MARS) = true in our SQL connection string (SQL 2005 or later) allows the execution of multiple batches on a single connection, which eliminates our error and allows the load test to run successfully. We all however agree that this doesn’t feel like the 100% correct solution, so we will be using this as an interim fix while we research more robust ways to make sure Linq’s DataContext’s lifecycle is correctly managed.