从数据库读取数据Table后转成对应的实体泛型方法

1 每次读取数据库的数据都是一个DataTable表,以前是傻傻的每个表都写一个转换的类,后来自己研究一个泛型方法,适用于所有转换

      /// <summary>
       /// 返回一个集合
       /// </summary>
       /// <typeparam name="T2">要传入的实体</typeparam>
       /// <param name="strSql">sql语句或者存储过程类型</param>
       /// <param name="sqlComType">sql语句或者存储过程类型</param>
       /// <param name="pars">Sql参数数组</param>
       /// <returns></returns>
       public static List<T2> ExcuteList<T2>(string strSql, CommandType sqlComType, ref string errMsg, params SqlParameter[] pars)
       {
           try
           {
               using (SqlConnection conn = new SqlConnection(s_ConnectionString))
               {
                   SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
                   if (pars != null)
                   {
                       sda.SelectCommand.Parameters.AddRange(pars);
                   }
                   sda.SelectCommand.CommandType = sqlComType;
                   DataTable dt = new DataTable();
                   sda.Fill(dt);
                   if (dt.Rows.Count > 0)
                   {
                       List<T2> list = new List<T2>();
                       Type t = typeof(T2);
                       foreach (DataRow dr in dt.Rows)
                       {
                           T2 model = (T2)Activator.CreateInstance(t);
                           PropertyInfo[] pros = t.GetProperties();
                           foreach (PropertyInfo p in pros)
                           {
                               string colName = p.Name;
                               if (dt.Columns.Contains(colName))
                               {
                                   if (p.CanWrite == false) continue;
                                   object cellValue = dr[colName];
                                   if (cellValue != DBNull.Value)
                                   {
                                       p.SetValue(model, cellValue, null);
                                   }
                               }
                           }
                           list.Add(model);
                       }
                       return list;
                   }
                   else
                   {
                       return null;
                   }
               }
           }
           catch (Exception ex)
           {
               errMsg =    ex.ToString();
               return null;
           }
       }

调用
   public IList<C_AccountModel> GetAccountList(ref string errMsg)
        {
            return C_SQLHelper.ExcuteList<C_AccountModel>("select * from Account  order by ID desc ", CommandType.Text, ref errMsg, null);
        }

  2 注意的地方

       a: 数据库表的字段必须与实体一样否则反射的时候装载不了。

 
原文地址:https://www.cnblogs.com/cdaq/p/6033615.html