简体   繁体   中英

C# SQLite vs DataTable: 'Specified cast is not valid.'

I have a problem with getting value from a DataTable row.

This is the query:

SELECT COALESCE((FE1), 0) + COALESCE((FE2), 0) + COALESCE((FEE), 0) 
FROM DRC 
WHERE DTS = '2021-04-21T09:57:47+02:00'

In DB Browser, it returns the following value: -5700 (as expected)

With different timestamp it may also result values in 2 decimals, therefore I decided to cast it to decimal while I retrieve it from DataTable.

But the below code throws an error

Specified cast is not valid.

...
string dts = "2021-04-21T09:57:47+02:00"
decimal sum = 0; 

query=$"SELECT COALESCE((FE1),0)+ COALESCE((FE2),0) +  COALESCE((FEE),0) FROM DRC WHERE DTS =  '{dts}'";
 
DataTable dt = new DataTable();
SQLiteCommand cmd = new SQLiteCommand(query, con);
SQLiteDataReader reader = cmd.ExecuteReader();
dt.Load(reader);

foreach (DataRow row in dt.Rows)
{
     sum = row.Field<decimal>(0); // Exception: System.InvalidCastException: 'Specified cast is not valid.'
}
...

With eg. integer, double etc type it results the same.

This is because you are performing a raw read, so the returned values in the DataTable will be typed as the underlying ORM chooses to represent them - in this case probably a SQLiteDecimal struct or similar.

I don't understand why you're even using a DataTable though, since you're reading a single row of a single resultset. Just consume the SQLiteDataReader directly:

using (var cmd = new SQLiteCommand(query, con))
{
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            sum = reader.GetDecimal(0);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM