#region DataReader转实体<T>
/// <summary>
/// DataReader转实体
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="dr">DataReader</param>
/// <returns>实体对象</returns>
public static T DataReaderToEntity<T>(IDataReader dr) where T : new()
{
T t = new T();
if (dr == null) return default(T);
using (dr)
{
if (dr.Read())
{
// 获得实体的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
List<string> listFieldName = new List<string>(dr.FieldCount);
for (int i = 0; i < dr.FieldCount; i++)
{
listFieldName.Add(dr.GetName(i).ToLower());
}
foreach (PropertyInfo p in propertys)
{
string columnName = p.Name;
if (listFieldName.Contains(columnName.ToLower()))
{
// 判断此属性是否有Setter或columnName值是否为空
object value = dr[columnName];
if (!p.CanWrite || value is DBNull || value == DBNull.Value) continue;
try
{
#region SetValue
switch (p.PropertyType.ToString())
{
case "System.String":
p.SetValue(t, Convert.ToString(value), null);
break;
case "System.Int32":
p.SetValue(t, Convert.ToInt32(value), null);
break;
case "System.Int64":
p.SetValue(t, Convert.ToInt64(value), null);
break;
case "System.DateTime":
p.SetValue(t, Convert.ToDateTime(value), null);
break;
case "System.Boolean":
p.SetValue(t, Convert.ToBoolean(value), null);
break;
case "System.Double":
p.SetValue(t, Convert.ToDouble(value), null);
break;
case "System.Decimal":
p.SetValue(t, Convert.ToDecimal(value), null);
break;
default:
p.SetValue(t, value, null);
break;
}
#endregion
}
catch
{
//throw (new Exception(ex.Message));
}
}
}
}
}
return t;
}
#endregion