Created
January 24, 2012 16:23
-
-
Save duncansmart/1670953 to your computer and use it in GitHub Desktop.
Returns, and converts as appropriate, the value of the supplied data record (DataReader) that corresponds with the named column
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
internal static class DataReaderUtil | |
{ | |
public static T GetValue<T>(this IDataRecord record, string columnName) | |
{ | |
T result = default(T); | |
int ordinal = record.GetOrdinal(columnName); | |
if (record.IsDBNull(ordinal)) | |
return result; | |
Type targetType = typeof(T); | |
// Convert.ChangeType() can't handle Enums | |
if (result is Enum) | |
{ | |
targetType = typeof(int); | |
} | |
// Nullable? Convert.ChangeType() can't handle those either... | |
else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>)) | |
{ | |
targetType = targetType.GetGenericArguments().First(); | |
} | |
try | |
{ | |
result = (T)Convert.ChangeType(record.GetValue(ordinal), targetType); | |
} | |
catch (FormatException ex) | |
{ | |
throw new FormatException(string.Format("Error converting {0} to {1}.", columnName, targetType), ex); | |
} | |
catch (InvalidCastException ex) | |
{ | |
throw new FormatException(string.Format("Error converting {0} to {1}.", columnName, targetType), ex); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment