using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; /// <summary>
///TestTableModel 的摘要说明
/// </summary>
public class TestTableModel
{
public int D_Id { get; set; }
public string D_Name { get; set; }
public string D_Password { get; set; }
public string D_Else { get; set; }
public decimal D_Amount { get; set; }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection; namespace MSCL
{
/// <summary>
///ObjectToList 的摘要说明
/// </summary>
public static class ObjectToList
{
/* --示例
IDataReader dr = MSCL.SqlHelper.GetSqlDataReader("select * from TestTable where d_id in(6,7,8)");
List<TestTableModel> t1 = MSCL.ObjectToList.DataReaderToList<TestTableModel>(dr);
for (int i = 0; i < t1.Count; i++)
{
Response.Write(t1[i].D_Id + "<br/>");
Response.Write(t1[i].D_Name + "<br/>");
Response.Write(t1[i].D_Password + "<br/>");
Response.Write(t1[i].D_Else + "<br/>");
Response.Write(t1[i].D_Amount + "<br/>");
}
dr.Dispose();
dr.Close();
*/ /// <summary>
/// DataReader利用泛型填充实体类
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="reader">DataReader</param>
/// <returns></returns>
public static List<T> DataReaderToList<T>(IDataReader reader)
{
//实例化一个List<>泛型集合
List<T> DataList = new List<T>();
while (reader.Read())
{
T RowInstance = Activator.CreateInstance<T>();//动态创建数据实体对象
//通过反射取得对象所有的Property
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
try
{
//取得当前数据库字段的顺序
int Ordinal = reader.GetOrdinal(Property.Name);
if (reader.GetValue(Ordinal) != DBNull.Value)
{
//将DataReader读取出来的数据填充到对象实体的属性里
Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
}
}
catch
{
break;
}
}
DataList.Add(RowInstance);
}
return DataList;
} /// <summary>
/// DataTable利用泛型填充实体类
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> DataTableToList<T>(DataTable dt) where T : new()
{
var list = new List<T>();
if (dt == null) return list;
var len = dt.Rows.Count; for (var i = 0; i < len; i++)
{
var info = new T();
foreach (DataColumn dc in dt.Rows[i].Table.Columns)
{
var field = dc.ColumnName;
var value = dt.Rows[i][field].ToString();
if (string.IsNullOrEmpty(value)) continue;
if (IsDate(value))
{
value = DateTime.Parse(value).ToString();
} var p = info.GetType().GetProperty(field); try
{
if (p.PropertyType == typeof(string))
{
p.SetValue(info, value, null);
}
else if (p.PropertyType == typeof(int))
{
p.SetValue(info, int.Parse(value), null);
}
else if (p.PropertyType == typeof(bool))
{
p.SetValue(info, bool.Parse(value), null);
}
else if (p.PropertyType == typeof(DateTime))
{
p.SetValue(info, DateTime.Parse(value), null);
}
else if (p.PropertyType == typeof(float))
{
p.SetValue(info, float.Parse(value), null);
}
else if (p.PropertyType == typeof(double))
{
p.SetValue(info, double.Parse(value), null);
}
else
{
p.SetValue(info, value, null);
}
}
catch (Exception)
{
//p.SetValue(info, ex.Message, null);
}
}
list.Add(info);
}
dt.Dispose(); dt = null;
return list;
} /// <summary>
/// 是否是时间
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
private static bool IsDate(string d)
{
DateTime d1;
double d2;
return !double.TryParse(d, out d2) && DateTime.TryParse(d, out d1);
}
}
}

DataReader,DataTable利用泛型填充实体类的更多相关文章

  1. 用DataTable填充实体类List

    /// <summary> /// 用DataTable填充实体类List /// </summary> public static List<T> FillLis ...

  2. C# 将DataTable数据源转换成实体类

    using System; using System.Collections.Generic; using System.Data; using System.Reflection; /// < ...

  3. DataTable填充实体类返回泛型集合

    昨天找坤哥看到我的一段代码.例如以下: 略微解释下,这段代码时D层查询结束后,将datatable查询到的结果赋值给实体对象的属性,然后返回实体的过程.坤哥看了之后问我.假设实体有500多个属性.难道 ...

  4. c#自定义ORM框架---(泛型&反射&实体类扩展属性<附带通用增、删、查、改>)

    该教材主要是运用到泛型.反射和实体类扩展属性 步骤一.建立扩展属性类 实体类扩展属性要继承Attribute基类完成 [AttributeUsage(AttributeTargets.Property ...

  5. (转)DataTable与结构不同实体类之间的转换

    原文地址:http://www.cnblogs.com/kinger906/p/3428855.html 在实际开发过程中,或者是第三方公司提供的数据表结构,与我们系统中的实体类字段不对应,遇到这样我 ...

  6. DataTable与结构不同实体类之间的转换

    在实际开发过程中,或者是第三方公司提供的数据表结构,与我们系统中的实体类字段不对应,遇到这样我们怎么处理呢?可能有人会说,在转换时创建一个实体对象,对表里的数据逐行遍历来实例化这个实体对象不就完了.的 ...

  7. 使用hibernate利用实体类生成表和利用表生成实体类

    1,配置数据库,这里以oracle数据库为例.点击右侧Database图标:

  8. [04] 利用注解生成实体类对应的建表sql语句

    1.实现功能 我们已经对注解有了基本的认识,知道了如何自定义注解,如何使用和最基本的处理注解. 本篇主要介绍,如何使用运行时级别的注解,配合反射来自动生成建表的sql语句.如下例: 我们有实体类Stu ...

  9. C#利用反射获取实体类的主键名称或者获取实体类的值

    //获取主键的 PropertyInfo PropertyInfo pkProp = ).FirstOrDefault(); //主键名称 var keyName=pkProp.Name; //实体类 ...

随机推荐

  1. CSS Filter

    支持的效果有: blur(模糊) grayscale(灰度) drop-shadow(阴影) sepia(褐色滤镜) brightness(亮度) contrast(对比) hue-rotate(色相 ...

  2. 树莓派安装ftp服务器

    在树莓派安装ftp服务器,可上载\下载文件 vsftpd是开源的轻量级的常用ftp服务器. 1,安装vsftpd服务器 (约400KB)sudo apt-get install vsftpd 2,启动 ...

  3. 浙江工商大学15年校赛I题 Inversion 【归并排序求逆序对】

    Inversion Time Limit 1s Memory Limit 131072KB Judge Program Standard Ratio(Solve/Submit) 15.00%(3/20 ...

  4. wget -r -nc -np "http://www.zhihu.com/"

    下载网站所有 -r,  --recursive          specify recursive download. -nc, --no-clobber              skip dow ...

  5. Ruby学习-第二章

    第二章 类继承,属性,类变量 1.如何声明一个子类 class Treasure < Thing 这样Thing类中的属性name,description都被Treasure继承 2.以下三种方 ...

  6. ORACLE列值合併

    合併列值最通用的方法就是寫一個自定義函數去實現,這裏介紹的是其它方法. 在SQL Server中合併列值能够使用For Xml Path,在Oracle中則能够使用wm_concat 或 ListAg ...

  7. android使用自己定义属性AttributeSet

    这里为了演示使用自己定义变量,字体大小改用自己定义的属性. 首先要创建变量,创建了个values/attrs.xml文件,文件名称随意,可是要在values文件夹下: <?xml version ...

  8. 在eclipse上安装 sdk出现的各种问题

    在eclipse上下进行android开发需要  有android SDK 和ADT 一般adt版本瑶台低, 会被提示安装较高版本的ADT,  不然, SDK可能无法使用 在安装 SDK过程中出现这样 ...

  9. C - 链表,推荐

    Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Status Descr ...

  10. python几个特别函数map filter reduce lambda

    lambda函数也叫匿名函数,即,函数没有具体的名称.先来看一个最简单例子: def f(x): return x**2 print f(4) Python中使用lambda的话,写成这样 g = l ...