What will be best way to Get Value from Sql Data reader?
I wrote a utility function to retrieve Value by column Name in underlying data type , anyone please suggest improvements in it.
The thing i consider inefficient is giving implementation for each type separately which will leave many types un handled,
Can My Code give compile type error for types which I did not handled? I considered using Generic Constraints but they are not help full in my case.
public static T GetValue<T>(SqlDataReader reader, string columnName,T defaultValue=default(T))
{
int ordinal;
//checking whether column name exist in reader result set
try
{
ordinal = reader.GetOrdinal(columnName);
}
catch (IndexOutOfRangeException coulmnException)
{
var innerexception =
new IndexOutOfRangeException(
String.Format("Coulumn Name does not exist in specified sql reader, {0}", coulmnException.Message),
coulmnException
);
throw innerexception;
}
catch (Exception e)
{
throw e;
}
//Defining Types and their crossponding functions to be called.
var typeDictionary = new Dictionary<Type, Func<T>>
{
{typeof(Int16), () => (T)Convert.ChangeType(reader.GetInt16(ordinal),typeof(T))},
{typeof(Int32), () => (T)Convert.ChangeType(reader.GetInt32(ordinal),typeof(T))},
{typeof(Int64), () => (T)Convert.ChangeType(reader.GetInt64(ordinal),typeof(T))},
{typeof(String), () => (T)Convert.ChangeType(reader.GetString(ordinal),typeof(T))},
{typeof(Boolean), () => (T)Convert.ChangeType(reader.GetBoolean(ordinal),typeof(T))},
{typeof(Byte), () => (T)Convert.ChangeType(reader.GetByte(ordinal),typeof(T))},
{typeof(DateTime), () => (T)Convert.ChangeType(reader.GetDateTime(ordinal),typeof(T))},
{typeof(Char), () => (T)Convert.ChangeType(reader.GetChar(ordinal),typeof(T))},
{typeof(Decimal), () => (T)Convert.ChangeType(reader.GetDecimal(ordinal),typeof(T))},
{typeof(Double), () => (T)Convert.ChangeType(reader.GetDouble(ordinal),typeof(T))}
};
Type providedType = typeof (T);
//Handling Nullable Types, If programmer wants to pass null value as default he should pass struct type with '?'.
if (providedType.IsGenericType && providedType.GetGenericTypeDefinition() == typeof (Nullable<>))
{
providedType = Nullable.GetUnderlyingType(providedType);
}
if (typeDictionary[providedType]==null)
{
throw new ArgumentException("Not Supported Type");
}
var resultedValue = reader.IsDBNull(ordinal) ? defaultValue : typeDictionary[typeof (T)]();
return resultedValue;
}
Blockquote
Aucun commentaire:
Enregistrer un commentaire