Here is a method that I created to read DBNull
and return a default(T)
incase:
private T GetNullable<T>(MySqlDataReader reader, int ordinal, Func<int, T> getValue)
{
if (reader.IsDBNull(ordinal))
{
return default(T);
}
return getValue(ordinal);
}
It can be used like this:
if (reader.Read())
{
account = new Account();
account.Id = reader.GetInt32(0);
account.Name = reader.GetString(1);
account.MailVerifiedAt = GetNullable(reader, 2, reader.GetDateTime);
account.MailToken = GetNullable(reader, 3, reader.GetString);
}
The generic type T
will be resolved based on the return value of the reader.
- method. If it returns a string you will receive a null
incase of DBNull
. If it is an int
it will return 0
, etc.
Note: for integer values it might not be desired to get a 0
so be careful.