Sunday, June 12, 2016

Entity Framework error ‘There is already an open DataReader associated with this Command which must be closed first.’

Had an error on a WebAPI call, which suddendly appeared, when attempting to get a list of Users from standard Identity Framework code.

There was the ususal massive (and almost completely useless) outer exception of "Error getting value from 'Claims' on 'System.Data.Entity.DynamicProxies.ApplicationUser_7215CB73076794A910D6058DEA10BE4541B79EFD3A2E64C8BB0403E9276DE20E'.” and within that "An error occurred while executing the command definition. See the inner exception for details”. Until finally we got to the base error "There is already an open DataReader associated with this Command which must be closed first.” of type System.InvalidOperationException.

After a few minutes scrating my head trying to figure out what was wrong, changing connection strings and trying to shut down all connections I came across a new option that can be added to the connection string, which was "MultipleActiveResultSets=True” (https://msdn.microsoft.com/en-ie/data/jj556606.aspx).

Changing the string from:
Server=(LocalDb)\MSSQLLocalDB;Database=<name>;Trusted_Connection=True
to
Server=(LocalDb)\MSSQLLocalDB;Database=<name>;Trusted_Connection=True;MultipleActiveResultSets=True;

Addressed the issue; I’m not 100% on the impact of this change, but it seems to fix the error and have no obvious down side.