I am trying to read a boolean
value from ODBCDataReader
by using ODBCDataReader.GetBoolean(i)
in theory it should work fine as the column we have read is a boolean column
and the data coming in is either 1
or 0
so when I read it like this -
return reader.IsDBNull(col) ? null : reader.GetBoolean(col);
I get InvalidCastException
Then I tried to fetch reader as
return reader.IsDBNull(col) ? null : Convert.ToBoolean(reader.GetValue(col));
The above line complains about The string is not recognized as a valid bool value.
(value is "1")
Then I wrote the following method --
public static bool? GetDbSafeNullableBit(this IDataRecord reader, string propertyName, bool? defaultBool = null)
{
var returnValue = defaultBool;
var col = reader.GetOrdinal(propertyName);
if (reader.IsDBNull(col))
{
return returnValue;
}
var stringValue = reader[col].ToString();
switch (stringValue)
{
case "1":
returnValue = true;
break;
case "0":
returnValue = false;
break;
default:
throw new Exception($"Value read from reader is not defined as proper boolean, value is {stringValue}");
}
return returnValue;
}
and Voila, I find this works fine.
Can someone please guide me on why the first two ways are not giving the expected result.
PS: Data is coming from PostgresSql (makes any difference ?)