DataTable转换为List的通用类

把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便。

所以很多人都是按照以下方式做的:

// 获得查询结果
DataTable dt = DbHelper.ExecuteDataTable(...);
// 把DataTable转换为IList<UserInfo>
IList<UserInfo> users = ConvertToUserInfo(dt);

问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为此模型的方法吗?

解决:能不能写个通用类,可以把DataTable转换为任何模型,呵呵,这就需要利用反射和泛型



+展开
-C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
 
namespace NCL.Data
{
     /// 
     /// 实体转换辅助类
     /// 
     public class ModelConvertHelper where   T : new ()
      {
         public static IList ConvertToModel(DataTable dt)
          {
             // 定义集合
              IList ts = new List();
 
             // 获得此模型的类型
              Type type = typeof (T);
 
             string tempName = "" ;
 
             foreach (DataRow dr in dt.Rows)
              {
                  T t = new T();
 
                 // 获得此模型的公共属性
                  PropertyInfo[] propertys = t.GetType().GetProperties();
 
                 foreach (PropertyInfo pi in propertys)
                  {
                      tempName = pi.Name;
 
                     // 检查DataTable是否包含此列
                     if (dt.Columns.Contains(tempName))
                      {
                         // 判断此属性是否有Setter
                         if (!pi.CanWrite) continue ;
 
                         object value = dr[tempName];
                         if (value != DBNull.Value)
                              pi.SetValue(t, valuenull );
                      }
                  }
 
                  ts.Add(t);
              }
 
             return ts;
 
          }
      }
}


使用方式:

+展开
-C#
// 获得查询结果
DataTable dt = DbHelper.ExecuteDataTable(...);
// 把DataTable转换为IList
IList users = ModelConvertHelper.ConvertToModel(dt); 


来源:http://www.cnblogs.com/fishtreeyu/archive/2011/03/11/1981068.html

加支付宝好友偷能量挖...


评论(0)网络
阅读(196)喜欢(0)Asp.Net/C#/WCF