Nullable integer values from reader
I use a generic extension method for all DB casts:
public static T? DbCast<T>(this object dbValue)
where T : struct
{
if (dbValue == null)
{
return null;
}
if (dbValue is System.DBNull)
{
return null;
}
T? value = dbValue as T?;
if (value != null)
{
return value;
}
var conv = dbValue as IConvertible;
if (conv != null)
{
value = (T)conv.ToType(typeof(T), CultureInfo.InvariantCulture);
}
return value;
}
It tries to treat every situation we encountered so far. Adjust conditions as needed for you.
Usage:
int? value = reader["Mem_ResAdd4"].DbCast<int>()
Just convert it, like you do in previous row
mb.Mem_ResAdd4 = reader["Mem_ResAdd4"] == System.DBNull.Value ? null : (string)reader["Mem_ResAdd4"];
//
mb.Mem_ResPin = reader["Mem_ResPin"]== System.DBNull.Value ? default(int):(int)reader["Mem_ResPin"]