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?
for the SqlDataReader.GetString Method, No conversions are performed; therefore, the data retrieved must already be a string.Call IsDBNull to check for null values before calling this method.Change you code to this and it should work
.NET 4.0 GetString() may cause errors / bugs in .NET 4.0 I would try rolling the project back to ver 3.5 or create a project that uses the code sample and create it as .NET 3.5, if this works with the
GetString()I have found that there are some bugs in .net 4.0 and I am not sure when the KB Fix is going to release