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

        }

    }

  • 相关阅读:
    Windows编程中UNICODE和_UNICODE定义问题
    关于暗时间
    一种简单的图像显著性计算模型
    L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到了一个处理错误
    L2TP连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到了一个处理错误
    Python正则表达式指南
    【Python】解压文件/ZIP等 并实时计算解压进度
    使用html2canvas和jsPdf实现打印功能
    Windows Phone 7 开发资源汇总
    批量删除数据库中有特定开始字符的表、视图和存储过程
  • 原文地址:https://www.cnblogs.com/jackljf/p/4768614.html
Copyright © 2011-2022 走看看