Skip to content

Instantly share code, notes, and snippets.

@x-a-n-d-e-r-k
Created May 1, 2012 02:10
Show Gist options
  • Save x-a-n-d-e-r-k/2564434 to your computer and use it in GitHub Desktop.
Save x-a-n-d-e-r-k/2564434 to your computer and use it in GitHub Desktop.
DbDataReader Extensions - Very Handy
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
public static class DbReaderExtensions {
public static string SafeGetString(this DbDataReader reader, string columnName) {
var index = reader.GetOrdinal(columnName);
return !reader.IsDBNull(index) ? reader.GetString(index) : string.Empty;
}
public static int? SafeGetNullableInt(this DbDataReader reader, string columnName) {
var index = reader.GetOrdinal(columnName);
return !reader.IsDBNull(index) ? (int?)reader.GetInt32(index) : null;
}
public static Guid? SafeGetNullableGuid(this DbDataReader reader, string columnName) {
var index = reader.GetOrdinal(columnName);
return !reader.IsDBNull(index) ? (Guid?)reader.GetGuid(index) : null;
}
public static DateTime? SafeGetNullableDateTime(this DbDataReader reader, string columnName) {
var index = reader.GetOrdinal(columnName);
return !reader.IsDBNull(index) ? (DateTime?)reader.GetDateTime(index) : null;
}
public static bool? SafeGetNullableBool(this DbDataReader reader, string columnName) {
var index = reader.GetOrdinal(columnName);
return !reader.IsDBNull(index) ? (bool?)reader.GetBoolean(index) : null;
}
public static Guid SafeGetGuid(this DbDataReader reader, string columnName) {
var index = reader.GetOrdinal(columnName);
return !reader.IsDBNull(index) ? reader.GetGuid(index) : Guid.Empty;
}
public static T Fill<T>(this DbDataReader reader, T obj) {
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
if (!prop.IsReadOnly) {
if (reader.HasColumn(prop.Name)) {
if (reader[prop.Name] is DBNull)
prop.SetValue(obj, null);
else
prop.SetValue(obj, reader[prop.Name]);
}
}
}
return obj;
}
public static bool HasColumn(this IDataRecord dr, string columnName) {
for (var i = 0; i < dr.FieldCount; i++) {
if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
}
@davecan
Copy link

davecan commented Jan 6, 2016

Very handy indeed! Also works on OdbcDataReader as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment