C# DataRow的扩展
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# DataRow的扩展相关的知识,希望对你有一定的参考价值。
/// <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;
}
以上是关于C# DataRow的扩展的主要内容,如果未能解决你的问题,请参考以下文章