1. 程式人生 > >DataTable 轉 實體集合 List<T> (反射)

DataTable 轉 實體集合 List<T> (反射)

 public static class Mapper
    {
        public static IEnumerable<T> DtToModels<T>(this DataTable dt) where T : class, new()
        {
            //判斷datatable是否有值
            if (dt.Columns.Count < 1 || dt.Rows.Count < 1)
            { yield break; }
            else
            {
                var propertyInfos = from propertyInfo in typeof(T).GetProperties()
                                    where dt.Columns.Contains(propertyInfo.Name)
                                    select propertyInfo;
                //迴圈設定屬性
                foreach (DataRow dr in dt.Rows)//遍歷dt中所有行
                {
                    var result = new T();
                    foreach (var p in propertyInfos)//遍歷所有屬性
                    {
                        try
                        {
                            if (p.PropertyType.Name == "Int64")
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToInt64(dr[p.Name]), null);
                            }
                            else if (p.PropertyType.Name == "Int32")
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToInt32(dr[p.Name]), null);
                            }
                            else if (p.PropertyType.Name == "Decimal")
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToDecimal(dr[p.Name]), null);
                            }
                            else
                            {
                                p.SetValue(result, dr[p.Name] == DBNull.Value ? null : dr[p.Name], null);
                            }

                        }
                        catch (System.Exception)
                        {

                            throw;
                        }
                    }
                    yield return result;
                }
            }
        }


    }

使用: