I’m trying to return a single row from a database:
using (connection = new SqlConnection(ConfigurationManager.AppSettings["connection"]))
{
using (command = new SqlCommand(@"select top 1 col_1, col_2 from table1", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
reader.Read();
return reader["col_1"];
}
}
}
But I’m getting the following error message:
Compiler Error Message: CS0266: Cannot implicitly convert type ‘object’ to ‘string’. An explicit conversion exists (are you missing a
cast?)
Line 90: return reader[“col_1”];
I’m sure I am making a really obvious mistake, but I can’t seem to find any single row examples, all I examples I find are for multiple returned rows using a while loop.
reader["col_1"]returnsobject.You want something like
reader.GetString(reader.GetOrdinal("col_1")).Edit -> I just wanted to add a note here that, in addition to the concerns others have raised, a
SELECT TOPwithout anORDER BYcan give you random results based on schema changes and/or merry-go-round scans.