C# DataTable转实体通用方法

       public static T GetEntity<T>(DataTable table) where T : new()
        {
            T entity = new T();
            foreach (DataRow row in table.Rows)
            {
                foreach (var item in entity.GetType().GetProperties())
                {
                    if (row.Table.Columns.Contains(item.Name))
                    {
                        if (DBNull.Value != row[item.Name])
                        {
                            Type tProperty = item.PropertyType; 
                            if (item.PropertyType.ToString() == "System.Nullable`1[System.DateTime]" && row[item.Name].GetType().ToString() == "System.DateTime")
                            {
                                tProperty = row[item.Name].GetType();
                            }
                            item.SetValue(entity, Convert.ChangeType(row[item.Name], tProperty), null);
                        }

                    }
                }
            }

            return entity;
        }

        public static IList<T> GetEntities<T>(DataTable table) where T : new()
        {
            IList<T> entities = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                T entity = new T();
                foreach (var item in entity.GetType().GetProperties())
                {
                    Type tProperty = item.PropertyType;
                    if (item.PropertyType.ToString() == "System.Nullable`1[System.DateTime]" && row[item.Name].GetType().ToString() == "System.DateTime")
                    {
                        tProperty = row[item.Name].GetType();
                    }
                    item.SetValue(entity, Convert.ChangeType(row[item.Name], tProperty), null);
                }
                entities.Add(entity);
            }
            return entities;
        }

  

posted @ 2017-01-12 14:45  RunningInSun  阅读(357)  评论(0编辑  收藏  举报