Latest Replies
Saturday
Dec062008

How to read value types from the DB

Snippet

/// <summary> Reads the column from <see cref="IDataReader"/>
/// as <see cref="Nullable{T}"/>. </summary>
public static T? ReadNullable<T>(this IDataReader reader, string name) 
  where T : struct
{
  Enforce.Argument(reader, "reader");
  Enforce.ArgumentNotEmpty(name, "name");

  var result = reader[name];
  return DBNull.Value == result ? default(T?) : (T) result;
}

/// <summary> Reads the column from <see cref="IDataReader"/>
/// as <see cref="Nullable{T}"/>. </summary>
public static T? ReadNullable<T>(this IDataReader reader, int index) 
  where T : struct
{
  Enforce.Argument(reader, "reader");
  Enforce.Argument(index, "index", Is.AtLeast(0));

  var result = reader[index];
  return DBNull.Value == result ? default(T?) : (T)result;
}

/// <summary> Reads the specified value-type from the reader, converting
/// <see cref="DBNull.Value"/> into the default value for this valueType.
/// </summary>
public static T Read<T>(this IDataReader reader, int index) 
  where T : struct
{
  Enforce.Argument(reader, "reader");
  Enforce.Argument(index, "index", Is.AtLeast(0));

  var result = reader[index];
  return DBNull.Value == result ? default(T) : (T) result;
}
/// <summary> Reads the specified value-type from the reader, converting
/// <see cref="DBNull.Value"/> into the default value for this valueType.
/// </summary>
public static T Read<T>(this IDataReader reader, string name) 
  where T : struct
{
  Enforce.Argument(reader, "reader");
  Enforce.ArgumentNotEmpty(name, "name");

  return reader.Read<T>(reader.GetOrdinal(name));
}

Usage

var total = reader.Read<int>("Total");
var optionalBonus = reader.ReadNullable<int>("Bonus");

This C# extensions snippet features:

« Dynamic Linq and Expression Parsing in .NET as a hint of C# compiler extensibility | Main | How to Use SystemUtil to Write .NET Code With Testable Sleep and Time Calls »