首页 > 代码库 > C#把 DataTable转换为Model实体

C#把 DataTable转换为Model实体

    public static List<T> GetModelFromDB<T>( DataTable dt )
        {
            List<T> data = http://www.mamicode.com/new List();"T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        private static T GetItem<T>(DataRow dr)
        {
            try
            {
                Type temp = typeof(T);
                T obj = Activator.CreateInstance<T>();
                foreach (DataColumn column in dr.Table.Columns)
                {
                    foreach (PropertyInfo pro in temp.GetProperties())
                    {
                        if (pro.Name.ToLower() == column.ColumnName.ToLower())
                        {
                            if (dr[column.ColumnName] == DBNull.Value)
                            {
                                pro.SetValue(obj, " ", null);
                                break;
                            }
                            else
                            {
                                pro.SetValue(obj, dr[column.ColumnName], null);
                                break;
                            }
                        }
                    }
                }
                return obj;
            }
           catch(Exception ex)
            {
              throw new Exception(ex.Message)
            }
        }

 

C#把 DataTable转换为Model实体