本帖最后由 Delver_Si 于 2015-4-21 16:09 编辑
给我什么类型的实体,返回什么类型的实体集合
- //得到一个list<T>
- public static List<T> getList<T>(string strSql)
- {
- List<T> list = new List<T>();
-
- SqlConnection sqlConn = new SqlConnection(strConn);
- SqlCommand sqlComm = new SqlCommand(strSql, sqlConn);
- sqlConn.Open();
- SqlDataReader sqlDR = sqlComm.ExecuteReader();
-
- while (sqlDR.Read())
- {
- //得到T的类型
- Type t = typeof(T); ;
-
- //查看类中的属性:
- PropertyInfo[] pis = t.GetProperties();
- // 用反射生成对象
- T model = Activator.CreateInstance<T>();
- foreach (PropertyInfo pi in pis)
- {
- if (pi!= null)
- {
- //取得特定字段并赋值
- pi.SetValue(model, sqlDR[pi.Name].ToString(), null);
- }
- }
-
- list.Add(model);
- }
- sqlConn.Close();
-
- return list;
-
- }
复制代码
整个DBHelp.cs- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data;
- using System.Data.SqlClient;
- using System.Reflection;
-
- namespace ManualAssign
- {
- public class DBHelp
- {
- //数据库连接字符串
- private static string strConn = "server=.;database=ManualAssign;integrated security=true";
-
- //得到一个DataTable
- public static DataTable getTable(string strSql)
- {
- SqlConnection sqlConn = new SqlConnection(strConn);
- SqlDataAdapter sqlDA = new SqlDataAdapter(strSql,sqlConn);
- DataTable dt = new DataTable();
- sqlDA.Fill(dt);
- return dt;
- }
-
- //增删改
- public static void upDateDB(string strSql)
- {
- SqlConnection sqlConn = new SqlConnection(strConn);
- SqlCommand sqlComm = new SqlCommand(strSql, sqlConn);
- sqlConn.Open();
- sqlComm.ExecuteNonQuery();
- sqlConn.Close();
- }
-
-
- //得到一个list<T>
- public static List<T> getList<T>(string strSql)
- {
- List<T> list = new List<T>();
-
- SqlConnection sqlConn = new SqlConnection(strConn);
- SqlCommand sqlComm = new SqlCommand(strSql, sqlConn);
- sqlConn.Open();
- SqlDataReader sqlDR = sqlComm.ExecuteReader();
-
- while (sqlDR.Read())
- {
- //得到T的类型
- Type t = typeof(T); ;
-
- //查看类中的属性:
- PropertyInfo[] pis = t.GetProperties();
- // 用反射生成对象
- T model = Activator.CreateInstance<T>();
- foreach (PropertyInfo pi in pis)
- {
- if (pi!= null)
- {
- //取得特定字段并赋值
- pi.SetValue(model, sqlDR[pi.Name].ToString(), null);
- }
- }
-
- list.Add(model);
- }
- sqlConn.Close();
-
- return list;
-
- }
-
- }
- }
复制代码
|