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

        }

    }

  • 相关阅读:
    git —— 远程仓库(操作)
    git —— 远程仓库(创建)
    git —— 异常1,index.lock
    git —— 基本命令以及操作(No.1)
    爬虫练习二(拉勾网投递简历)
    知识点拾忆(一)
    爬虫练习一(爬取笑话集)
    metaclass元类解析
    正则表达式re.S的用法
    requests模块
  • 原文地址:https://www.cnblogs.com/jackljf/p/4768614.html
Copyright © 2011-2022 走看看