I have a SQLite table with the following definition:
create table routes(id INTEGER PRIMARY KEY AUTOINCREMENT, name string)
and want to fetch records using System.Data.SQLite:
cmdRoute.CommandText = "SELECT id, name FROM routes";
using (var rdrRoute = cmdRoute.ExecuteReader())
{
if(rdrRoute.Read())
{
var route = new Route();
route.Id = rdrRoute.GetInt32(0);
route.Name = rdrRoute.GetString(1); // Throws InvalidCastException
}
}
The GetString throws an InvalidCastException when the value in the database is numeric.
When I put the rdrRoute.GetValue(1) in a watch, it shows that the type is "object {string}". When I change the value to a non-numeric value, it works fine.
I've looked in the SQLite DataReader code and it looks like SQLite checks the value to map it to a set of allowed types.
Is this the intended behaviour and how can I prevent this, in a way that strings containing numbers are still strings?
route.Name = rdrRoute.GetString(1).ToString();or try casting it as a string like thisroute.Name = (string)rdrRoute.GetString(1);rdrRoute.GetString(1)already crashes with the InvalidCastException.(string)rdrRoute.GetString(1);(string)rdrRoute.GetValue(1)works, but I want to know why theGetString(1)doesn't work.