I am connecting to an SQL Server 2012 database to query for a single value based on an ID. (It may be worth mentioning that this database is on a server on another continent from my development machine, and so latencies are quite high. Somewhere around 100ms).
The query appears to execute successfully. The HasRows property of the SqlDataReader object is set to true, so I try to use the value to assign a variable. When I run the program normally, I encounter an exception with message 'Given key was not present in the dictionary'. If I stop the execution and inspect the SqlDataReader object, and enumerate the results. Firstly I am told 'enumeration yielded no results' and then when I continue execution I get a different exception with the message 'invalid attempt to read when no data is present'
Here is the code in question:
SqlConnection sql_conn = new SqlConnection(ConnectionString);
SqlCommand sql_cmd = new SqlCommand(String.Format("select ItemType from ItemTable where ItemID='{0}'", item_id), sql_conn);
Console.WriteLine(sql_cmd.CommandText);
sql_conn.Open();
SqlDataReader rdr = sql_cmd.ExecuteReader();
rdr.Read();
if (rdr.HasRows) //True
{
item_type= TypesMap[rdr["ItemType"].ToString()]; //Either 'given key not found in dictionary' or 'invalid attempt to read when no data is present'
}
I have executed the SQL statement in SQL Server Management Studio and it is successful. I have tried hardcoding an ItemID into the statement in the C# code, and the same errors exist.
What more can I do to debug this? Everything appears to be okay, until I try to access the results of the query.
HasRowsto check if there are any rows and then useReadto advance the reader to the next record.if (reader.Read()) { item_type= TypesMap[rdr["ItemType"].ToString()]; }