zoukankan      html  css  js  c++  java
  • 【转】给DataTable和DataRow扩展方法,直接转换为对象集合或对象

    /// <summary>
    /// 类 说 明:给DataTable和DataRow扩展方法,直接转换为对象集合或对象
    /// 补充说明:此扩展类可以极大的简化操作,但是性能低下,大数据以及高性能要求下慎用.
    ///           此类如果放到asp.net的App_Code文件夹下会有编译错误,放到其他地方则无此问题
    /// </summary>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Reflection;
    
    namespace ChengChenXu.Blog.DAL
    {
        
        internal static class DataTableExtensions
        {
            /// <summary>
            /// 把DataRow直接转换成对应的实体对象,给DataRow添加一个扩展方法,方便使用.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dr"></param>
            /// <returns></returns>
            internal static T ToModel<T>(this DataRow dr)
            {
                T t = Activator.CreateInstance<T>();
                // 利用反射获得此模型的公共属性  
                string attributeName = String.Empty;
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    attributeName = pi.Name;
                    // 检查DataTable是否包含此列
                    //此处要求DataRow的列名称要和对象属性名称一致
                    //注意:此处大小写不敏感
                    if (dr.Table.Columns.Contains(attributeName))
                    {
                        // 判断此属性是否为只读(不包含set构造)  
                        if (!pi.CanWrite) { continue; }
    
                        //给属性赋值
                        var value = dr[attributeName];
                        if (value != DBNull.Value) 
                        { 
                            pi.SetValue(t, value,null); 
                        }
                    }
                }
                return t;
            }
    
            /// <summary>
            /// 将DataTable直接转化为对象集合
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dt"></param>
            /// <returns></returns>
            internal static List<T> ToModelList<T>(this DataTable dt)
            {
                List<T> list = new List<T>();
    
                //调用ToModel方法添加List
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    T t = Activator.CreateInstance<T>();
                    t = dt.Rows[i].ToModel<T>();
                    list.Add(t);
                }
    
                return list;
            }
        }
    }
    

     转自:http://chengchenxu.com

  • 相关阅读:
    Linux 的特殊变量(2)
    Shell 的特殊变量
    linux shell 基本规范
    Linux C 程序的开发环境
    编译和连接
    编程语言与C语言的简介
    Python条件判断和循环语句
    Python基本数据类型
    Java基本数据类型
    Jmeter(1)下载和安装
  • 原文地址:https://www.cnblogs.com/hycms/p/8596224.html
Copyright © 2011-2022 走看看