Question

Why is data read from SqlDataReader not available to a method call? I have a table, with 'id' as column in it. When I make a query to database, it returns rows.

This code doesnt work (Says 'id' column doesnt exist):

con.Open();
SqlDataReader requestReader = cmd.ExecuteReader();
if (requestReader.HasRows)
{
   DataTable requestTable = requestReader.GetSchemaTable();
   request = ReadRequest(requestTable.Rows[0]);        
}

con.Close();

while this one works:

con.Open();
SqlDataReader requestReader = cmd.ExecuteReader();
if (requestReader.HasRows)
{
   DataTable requestTable = requestReader.GetSchemaTable();
   var requestRow = requestTable.Rows[0];
   request = new Request();
   request.UniqueId = (string)requestRow["id"];
}

con.Close();
Was it helpful?

Solution

You are using DataReader.GetSchemaTable which returns a DataTable with all schema informations for a given table.

It has following columns:

ColumnName
ColumnOrdinal
ColumnSize
NumericPrecision
// .. 26 others

So you don't find your id-column which belongs to your table. That's why you get the error "'id' column doesnt exist". I doubt that your second approach works. I don't see why you need GetSchemaTable at all. You just have to advance the reader to the next record:

if (requestReader.HasRows && requestReader.Read())
{
   int id = requestReader.GetInt32(requestReader.GetOrdinal("id"));
   // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top