Tuesday, September 10, 2013

Extension Method for DB Reader

I was doing some quick and dirty data access for a demo program the other day. I was annoyed by having to call reader.IsDbNull() every time a DB field was a nullable simple type. My buddy Milenko and I created the following to make things look a little neater:

public static class ExtensionMethods
{
    public static T? GetNullableValue(this IDataRecord reader, string fieldName) where  T: struct
    {
        int ordinal = reader.GetOrdinal(fieldName);
        if (reader.IsDBNull(ordinal))
        {
             return null;
        }
        return (T)reader.GetValue(ordinal);
    }
}

No comments: