现在的位置: 首页 > 综合 > 正文

利用反射实现通用的DataReader转List、DataReader转实体类

2013年06月18日 ⁄ 综合 ⁄ 共 1665字 ⁄ 字号 评论关闭

public static T ReaderToModel<T>(IDataReader dr)
{
try

{
using
(dr)
{
if
(dr.Read())
{
List<string> list = new List<string>
(dr.FieldCount);
for (int i = 0; i < dr.FieldCount; i++
)
{
list.Add(dr.GetName(i).ToLower());
}
T model = Activator.CreateInstance<T>
();
foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public |
BindingFlags.Instance))
{
if
(list.Contains(pi.Name.ToLower()))
{
if (!
IsNullOrDBNull(dr[pi.Name]))
{
pi.SetValue(model, HackType(dr[pi.Name], pi.PropertyType), null
);
}
}
}
return
model;
}
}
return default
(T);
}
catch
(Exception ex)
{
throw
ex;
}
}

public static List<T> ReaderToList<T>(IDataReader dr)
{
using
(dr)
{
List<string> field = new List<string>
(dr.FieldCount);
for (int i = 0; i < dr.FieldCount; i++
)
{
field.Add(dr.GetName(i).ToLower());
}
List<T> list = new List<T>
();
while
(dr.Read())
{
T model = Activator.CreateInstance<T>
();
foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public |
BindingFlags.Instance))
{
if
(field.Contains(property.Name.ToLower()))
{
if (!
IsNullOrDBNull(dr[property.Name]))
{
property.SetValue(model, HackType(dr[property.Name], property.PropertyType), null
);
}
}
}
list.Add(model);
}
return
list;
}
}
//这个类对可空类型进行判断转换,要不然会报错
private static object HackType(object
value, Type conversionType)
{
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>
)))
{
if (value == null
)
return null
;

System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
conversionType =
nullableConverter.UnderlyingType;
}
return
Convert.ChangeType(value, conversionType);
}

private static bool IsNullOrDBNull(object obj)
{
return ((obj is DBNull) || string.IsNullOrEmpty(obj.ToString())) ? true : false
;
}

抱歉!评论已关闭.