public static class SqlReaderExtensionMethods
{
public static T GetValue(this SqlDataReader reader, int i)
{
var result = reader.GetValue(i);
return result is DBNull ? default(T) : (T)result;
}
public static T GetValue(this SqlDataReader reader, string columnName)
{
if (string.IsNullOrWhiteSpace(columnName))
throw new ArgumentNullException();
int columnIndex = reader.GetOrdinal(columnName);
var result = reader.GetValue(columnIndex);
return result is DBNull ? default(T) : (T)result;
}
public static void GetValue(this SqlDataReader reader,out T property)
{
property = GetValue(reader, nameof(property));
}
public static void MapClass(this SqlDataReader reader, ref T obj, bool mapAlsoStaticProperties = false) where T : class
{
var properties = typeof(T).GetProperties().Where
(
q => q.CanWrite == true
&& mapAlsoStaticProperties ? true : !q.GetAccessors(true)[0].IsStatic
).Select(q => q.Name);
foreach (var propName in properties)
{
var prop = obj.GetType().GetProperty(propName);
int columnIndex = reader.GetOrdinal(propName);
var result = reader.GetValue(columnIndex);
prop.SetValue(obj, result is DBNull ? GetDefault(prop.GetType()) : result, null);
}
}
private static object GetDefault(Type type)
{
if (type.IsValueType)
return Activator.CreateInstance(type);
return null;
}
}
//KULLANIM ŞEKLİ
result = new List<LABSONUC>();
if (reader.HasRows)
while (reader.Read())
{
var ls = new LABSONUC();
reader.MapClass(ref ls);
yield return ls;
}