Created
May 1, 2012 02:10
-
-
Save x-a-n-d-e-r-k/2564434 to your computer and use it in GitHub Desktop.
DbDataReader Extensions - Very Handy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very handy indeed! Also works on OdbcDataReader as well.