using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Reflection; using System.Web; namespace DAL { /// <summary> /// 职责:封装所有Dal的公共的CRUD方法 /// </summary> public class BaseDal<T> where T : class,new() { readonly string constr = ConfigurationManager.AppSettings["LocalConnectionString"]; /// <summary> /// 几乎所有的需要返回数据的方法都可以用这个方法 /// </summary> /// <param name="sqlStr"></param> /// <param name="Parameters"></param> /// <returns></returns> public List<T> GetData(string sqlStr, List<SqlParameter> Parameters) { List<T> data = null; DataTable dt = Query(constr, sqlStr, Parameters); Type type = typeof(T);//获取类型 string tempName = string.Empty;//定义临时变量 foreach (DataRow dr in dt.Rows) { T t = new T(); PropertyInfo[] pty = t.GetType().GetProperties();//获得此类型的公共属性 foreach (PropertyInfo pi in pty)//遍历该对象的所有属性 { tempName = pi.Name;//将属性名称赋值给临时变量 if (dt.Columns.Contains(tempName))//检查表中是否包含此列 { if (!pi.CanWrite) continue;//判断该属性是否可写,若不可写直接跳出 pi.SetValue(t, dr[tempName], null); //object value = dr[tempName]; //if (value != DBNull.Value)//如果是非空,则赋值给对象的属性 //pi.SetValue(t, value, null); } } } return data; } #region SqlHelper中的内容 public DataTable Query(string connStr, string sqlStr, List<SqlParameter> Paras) { SqlConnection conn = new SqlConnection(connStr); conn.Open(); try { SqlCommand comm = new SqlCommand(sqlStr, conn); SqlDataAdapter da = new SqlDataAdapter(comm); DataTable dt = new DataTable(); da.Fill(dt); return dt; } catch (Exception ex) { throw ex; } finally { conn.Close(); } } #endregion } }