zoukankan      html  css  js  c++  java
  • 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)

    转:http://www.cnblogs.com/the7stroke/archive/2012/04/22/2465591.html

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Data;

    using System.Reflection;

    namespace System.Data

    {

        public static class DataTableHelper

        {

            #region 利用反射把DataTable的数据写到单个实体类

            public static T ToSingleEntity<T>(this System.Data.DataTable dtSource)

            {

                if (dtSource == null)

                {

                    return default(T);

                }

                if (dtSource.Rows.Count != 0)

                {

                    Type type = typeof(T);

                    Object entity = Activator.CreateInstance(type);         //创建实例               

                    foreach (PropertyInfo entityCols in type.GetProperties())

                    {

                        if (!string.IsNullOrEmpty(dtSource.Rows[0][entityCols.Name].ToString()))

                        {

                            entityCols.SetValue(entity, Convert.ChangeType(dtSource.Rows[0][entityCols.Name], entityCols.PropertyType), null);

                        }

                    }

                    return (T)entity;

                }

                return default(T);

            }

            #endregion

            #region 利用反射把DataTable的数据写到集合实体类里

            public static List<T> ToListEntity<T>(this System.Data.DataTable dtSource)

            {

                if (dtSource == null)

                {

                    return null;

                }

                List<T> list = new List<T>();

                Type type = typeof(T);

                foreach (DataRow dataRow in dtSource.Rows)

                {

                    Object entity = Activator.CreateInstance(type);         //创建实例               

                    foreach (PropertyInfo entityCols in type.GetProperties())

                    {

                        if (!string.IsNullOrEmpty(dataRow[entityCols.Name].ToString()))

                        {

                            entityCols.SetValue(entity, Convert.ChangeType(dataRow[entityCols.Name], entityCols.PropertyType), null);

                        }

                    }

                    list.Add((T)entity);

                }

                return list;

            }

            #endregion

        }

    }

  • 相关阅读:
    Contest20140710 eagleeggs
    bzoj 1059: [ZJOI2007]矩阵游戏 二分图匹配
    Quick-Cocos2d-x初学者游戏教程(二) -------------------- Quick内部的代码结构及相应的原理
    Quick-Cocos2d-x初学者游戏教程(一)--------------------Quick的一些基础知识
    使用Cocos Studio 1.6 编辑人物属性界面
    Cocos2d-x 3.0 开发(十四)使用UIScrollView 实现大小不同物品拖动展示
    使用Cocos Studio 1.6 编辑开始界面
    Cocos2d-x Json用法
    Cocos2d-x xml解析
    plist文件操作
  • 原文地址:https://www.cnblogs.com/jackljf/p/4768614.html
Copyright © 2011-2022 走看看