1. 程式人生 > >對DataSet,DataRow,DateTable轉換成相應的模型

對DataSet,DataRow,DateTable轉換成相應的模型

        /// <summary>
        /// DataRow 轉成 模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ToModel<T>(this DataRow dr) where T : class, new()
        {
            T ob = new T();
            if (dr != null)
            {
                Type vType = typeof(T);
                //建立一個屬性的列表
                PropertyInfo[] prlist = vType.GetProperties();


                DataColumnCollection vDataCoulumns = dr.Table.Columns;
                try
                {
                    foreach (PropertyInfo vProInfo in prlist)
                    {
                        if (vDataCoulumns.IndexOf(vProInfo.Name) >= 0 && dr[vProInfo.Name] != DBNull.Value)
                        {
                            vProInfo.SetValue(ob, dr[vProInfo.Name], null);
                        }
                    }
                }
                catch (Exception ex)
                {


                }
            }
            return ob;
        }
        /// <summary>
        /// DataTable 轉換為List 集合
        /// </summary>
        /// <typeparam name="T">型別</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : class, new()
        {
            //建立一個屬性的列表
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //獲取TResult的型別例項  反射的入口
            Type t = typeof(T);
            //獲得TResult 的所有的Public 屬性 並找出TResult屬性和DataTable的列名稱相同的屬性(PropertyInfo) 並加入到屬性列表 
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            //建立返回的集合
            List<T> oblist = new List<T>();
            if (dt != null)
            {
                foreach (DataRow row in dt.Rows)
                {
                    try
                    {
                        //建立TResult的例項
                        T ob = new T();
                        //找到對應的資料  並賦值
                        prlist.ForEach(p =>
                        {
                            if (dt.Columns.IndexOf(p.Name) >= 0 && row[p.Name] != DBNull.Value)
                            {
                                try
                                {
                                    //如果是泛型
                                    if (p.PropertyType.ToString().IndexOf("System.Nullable") > -1)
                                    {
                                        string types = p.PropertyType.ToString().Substring(p.PropertyType.ToString().IndexOf("[") + 1);
                                        types = types.Substring(0, types.Length - 1);


                                        Type typeinfo = Type.GetType(types);
                                        p.SetValue(ob, Convert.ChangeType(row[p.Name], typeinfo), null);


                                    }
                                    else
                                    {
                                        p.SetValue(ob, Convert.ChangeType(row[p.Name], p.PropertyType), null);//型別轉換
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogUtility.WriteLogForExcepiton(ex);
                                }


                            }
                        });
                        //放入到返回的集合中.
                        oblist.Add(ob);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return oblist;
        }
        /// <summary>         
        /// DataSet轉換為泛型集合         
        /// </summary>         
        /// <typeparam name="T">泛型型別</typeparam>         
        /// <param name="ds">DataSet資料集</param>         
        /// <param name="tableIndex">待轉換資料表索引,預設第0張表</param>         
        /// <returns>返回泛型集合</returns>         
        public static IList<T> ToList<T>(this DataSet ds, int tableIndex = 0)
        {

            if (ds == null || ds.Tables.Count < 0) return null;
            if (tableIndex > ds.Tables.Count - 1)
                return null;

            if (tableIndex < 0)
                tableIndex = 0;

            DataTable dt = ds.Tables[tableIndex];

            // 返回值初始化             
            IList<T> result = new List<T>();
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertys = _t.GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {

                        // 屬性與欄位名稱一致的進行賦值                         
                        if (pi.Name.Equals(dt.Columns[i].ColumnName))
                        {

                            // 資料庫NULL值單獨處理                             
                            if (dt.Rows[j][i] != DBNull.Value)
                                pi.SetValue(_t, dt.Rows[j][i], null);
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }


        /// <summary>         
        /// DataSet轉換為泛型集合         
        /// </summary>         
        /// <typeparam name="T">泛型型別</typeparam>         
        /// <param name="ds">DataSet資料集</param>         
        /// <param name="tableName">待轉換資料表名稱,名稱為空時預設第0張表</param>         
        /// <returns>返回泛型集合</returns>         
        public static IList<T> ToList<T>(this DataSet ds, string tableName)
        {

            int _TableIndex = 0;

            if (ds == null || ds.Tables.Count < 0)
                return null;

            if (string.IsNullOrEmpty(tableName))
                return ToList<T>(ds, 0);

            for (int i = 0; i < ds.Tables.Count; i++)
            {

                // 獲取Table名稱在Tables集合中的索引值                 
                if (ds.Tables[i].TableName.Equals(tableName))
                {
                    _TableIndex = i;
                    break;
                }
            }
            return ToList<T>(ds, _TableIndex);
        }