I get a strange problem where I can return the results of a call from a stored procedure, but the code fails retrospectively.
public IEnumerable<T> ExecuteStoredProcedure<T>(string storedProcedureName, IDataMapper<T> mapper, IDictionary<string, object> parameters) { using (var connection = new SqlConnection(connectionString)) { using (var cmd = new SqlCommand(storedProcedureName, connection)) { cmd.CommandType = CommandType.StoredProcedure; foreach (var key in parameters.Keys) { cmd.Parameters.AddWithValue(key, parameters[key]); } connection.Open(); SqlDataReader reader = cmd.ExecuteReader();
Calling this code shows that the variable x always represents the number of lines that I expect to see from the call to my stored procedures.
In addition, my debug output shows the identifier values ββthat I expect to see.
However, after these results are returned, I get the error An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code from the line if (reader.HasRows) (i.e. already completed). The browser from which I call this request shows HTTP Error 502.3 - Bad Gateway .


I suspect the reason is a system that calculates the ID and x values ββfor debugging separately, as it will return real user output. Thus, it performs a lazy operation to get IEnumerable values ββat the moment when it should return them; only at this point using statements called the dispose methods, and therefore the connection to the reader is null (this is what I see when I check the properties of the reader variable during debugging).
Has anyone seen this behavior before / is this a bug? or did I just miss something obvious?
Additional code:
public interface IDataMapper<T> { T MapToDto(IDataRecord record); } public class CurrencyMapper: IDataMapper<CurrencyDTO> { const string FieldNameCode = "Code"; const string FieldNameId = "Id"; const string FieldNameName = "Name"; const string FieldNameNum = "Num"; const string FieldNameE = "E"; const string FieldNameSymbol = "Symbol"; public CurrencyMapper() { } public CurrencyDTO MapToDto(IDataRecord record) { var code = record[FieldNameCode] as string; var id = record[FieldNameId] as Guid?; var name = record[FieldNameName] as string; var num = record[FieldNameNum] as string; var e = record[FieldNameE] as int?; var symbol = record[FieldNameSymbol] as char?; return new CurrencyDTO(id, code, num, e, name, symbol); } } public class CurrencyRepository { const string SPReadAll = "usp_CRUD_Currency_ReadAll"; readonly SqlDatabase db; public CurrencyRepository() { db = new SqlDatabase();