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:
- generic methods with the constraint for value type
- default(T) syntax
- Argument checking syntax from the Validation and Business Rules Application Block.
Comments Off
Saturday, December 6, 2008 at 14:50