本人基本不写博客,今天实在没什么事情,分享一个泛型方法,此泛型方法,如有不妥之处敬请谅解。先贴代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Reflection;
using Sky.DBUtility;
namespace Sky.Data
{
    public class CeShi
    {
        public static List<T> GetCommon<T>(string sql) where T : class
        {
            List<T> list = null;
            using (SqlDataReader reader = DbHelper.ExecuteReader(sql))
            {
                if (reader.HasRows)
                {
                    list = new List<T>();
                    int colNum = reader.FieldCount;
                    while (reader.Read())
                    {
                        T obj = Activator.CreateInstance<T>();
                        Type type = obj.GetType();
                        for (int i = 0; i < colNum; i++)
                        {
                            string fieldName = reader.GetName(i);
                            PropertyInfo pinfo = type.GetProperty(fieldName);
                            string typeName = reader.GetDataTypeName(i);
                            switch (typeName)
                            {
                                case "nvarchar":
                                    pinfo.SetValue(obj, reader.GetString(i), null);
                                    break;
                                case "int":
                                    pinfo.SetValue(obj, reader.GetInt32(i), null);
                                    break;
                            }
                        }
                        list.Add(obj);
                    }
                }
            }
            return list;
        }
}
}
此方法还有不足之处,大家可以自己完善。
方法功能解释:我们经常需要查询数据,并且把查询数据返回一个实体类,方便操作,需要先得到一个SqlDataReader来循环给某个实体类赋值,感觉有时比较麻烦,尤其是数据库字段比较多的情况写起代码来非常的烦人。现在我们可以通过使用这个方法T对应我们的实体类,能过sql语句按照表字段来匹配对应的实体类的属性名,直接返回我们想要的实体方法。
如有疑问请发评论,感谢大家,第一次发贴言语组织上还有问题,望大家见谅。
2011/9/9 15:54:15 | asp.net | |
Type type = obj.GetType();
这两个可以放到while之外,看似重复的类型,可以重复用。