Random Noise

cat /dev/random >> /dev/dsp

IDataReader GetValue Extension method

with 2 comments

It is offten desired to get a value from DataReader using column name with known Type. For example you want to get a string value of column ‘first_name’ and int value of column ‘account_number’. The following extension method makes it easy to fetch values from a DataReader using Type and column name:

public static class ReaderHelper
{
    public static bool IsNullableType(Type valueType)
    {
        return (valueType.IsGenericType &&
            valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }

    public static T GetValue<T>(this IDataReader reader, string columnName)
    {
        object value = reader[columnName];
        Type valueType = typeof(T);
        if (value != DBNull.Value)
        {
            if (!IsNullableType(valueType))
            {
                return (T)Convert.ChangeType(value, valueType);
            }
            else
            {
                NullableConverter nc = new NullableConverter(valueType);
                return (T)Convert.ChangeType(value, nc.UnderlyingType);
            }
        }
        return default(T);
    }
}

It can be used as:

User GetUser(IDataReader reader)
{
    User user = new User();
    user.FirstName = reader.GetValue<string>("first_name");
    user.LastName = reader.GetValue<string>("last_name");
    user.Email = reader.GetValue<string>("email");
    user.AccountNumber = reader.GetValue<int>("account_number");
    user.NumberOfVehiclesOwned = reader.GetValue<int?>("vehicle_count"); // nullable data field
    return user;
}
Advertisements

Written by Vivek Unune

July 15, 2009 at 9:27 pm

Posted in .NET

Tagged with ,

2 Responses

Subscribe to comments with RSS.

  1. This looks interesting – have you conducted any performance testing on this?

    ActiveEngine Sensei

    July 16, 2009 at 1:46 am

    • No I haven’t. You can get rid of the nullable type checking and create two separate versions, a nullable type version and regular typed one. That should take fewer cycles.

      Vivek Unune

      July 16, 2009 at 2:35 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: