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

        }

    }

  • 相关阅读:
    网络请求侦听工具
    再转动画实现
    转如何解决EXC_BAD_ACCESS错误
    关于Iphone开发得一些案例及常用知识(转过来的参考用)
    用uiwebview打开pdf,word,excel
    转 iphone开发资料汇总(很多实用的东东)
    设置uiview背景图的方法之一
    给状态条加上图标的代码
    xcode 4 下找EXC_BAD_ACCESS错误原因
    linux&unix常用命令
  • 原文地址:https://www.cnblogs.com/jackljf/p/4768614.html
Copyright © 2011-2022 走看看