标签:
/// <summary>
/// 对于entity的一些常用的扩展方法
/// </summary>
public static class MyExtension
{
/// <summary>
/// 把DataRow转换成一个指定的实体类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
public static T ToEntity<T>(this DataRow dr)
{
var type = typeof (T);
var ins = Activator.CreateInstance<T>();
var pis = type.GetProperties();
foreach (PropertyInfo pi in pis)
{
var myProType = pi.PropertyType.Name.ToLower();
var colName = pi.Name;
object val = String.Empty;
var myAttr = pi.GetCustomAttributes<PropertyTypeAttribute>().FirstOrDefault();
if (myAttr != null)
{
if (!String.IsNullOrEmpty(myAttr.MyColName))
{
colName = myAttr.MyColName;
}
if (myAttr.MyType!=null)
{
myProType = myAttr.MyType.Name.ToLower();
}
}
if (!dr.Table.Columns.Contains(colName))
{
continue;
}
switch (myProType)
{
case "string"://String
val = dr[colName] == DBNull.Value ? String.Empty : dr[colName].ToString();
break;
case "int32"://int
val = dr[colName] == DBNull.Value ? 0 : Int32.Parse(dr[colName].ToString());
break;
case "int64"://long
val = dr[colName] == DBNull.Value ? 0 : Int64.Parse(dr[colName].ToString());
break;
case "decimal"://Decimal
val = dr[colName] == DBNull.Value ? Decimal.Zero : Decimal.Parse(dr[colName].ToString());
break;
case "double"://Double
val = dr[colName] == DBNull.Value ? 0 : Double.Parse(dr[colName].ToString());
break;
case "boolean"://Boolean
val = dr[colName] != DBNull.Value && Boolean.Parse(dr[colName].ToString());
break;
case "datetime"://DateTime
val = dr[colName] != DBNull.Value ? DateTime.Parse("1970-01-01 00:00:00") : DateTime.Parse(dr[colName].ToString());
break;
default:
break;
}
if (pi.CanWrite)
{
pi.SetValue(ins, val);
}
}
return ins;
}
标签:
原文地址:http://www.cnblogs.com/xiaozhuaweiliang/p/5568024.html