zoukankan      html  css  js  c++  java
  • C# 将DataTable数据源转换成实体类

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;
    
    /// <summary>
    /// 将DataTable数据源转换成实体类
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public static class ToModel<T> where T : new()
    {
        /// <summary>
        /// 将DataTable数据源转换成实体类
        /// </summary>
        public static List<T> ConvertToModel(DataTable dt)
        {
            List<T> ts = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pi in propertys)
                {
                    if (dt.Columns.Contains(pi.Name))
                    {
                        if (!pi.CanWrite) continue;
                        var value = dr[pi.Name];
                        if (value != DBNull.Value)
                        {
                            switch (pi.PropertyType.FullName)
                            {
                                case "System.Decimal":
                                    pi.SetValue(t, decimal.Parse(value.ToString()), null);
                                    break;
                                case "System.String":
                                    pi.SetValue(t, value.ToString(), null);
                                    break;
                                case "System.Int32":
                                    pi.SetValue(t, int.Parse(value.ToString()), null);
                                    break;
                                default:
                                    pi.SetValue(t, value, null);
                                    break;
                            }
                        }
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }
  • 相关阅读:
    转Vtype扩展
    Can't connect to MySQL server on 'ip' (13)
    观察者+js 模式
    (转)ASP.NET架构分析
    sql得到时间
    Js+XML 操作 (转)
    js中的math对象
    property和attribute的区别
    CSS样式定义
    linux 开启 mount
  • 原文地址:https://www.cnblogs.com/zhaoshujie/p/10606726.html
Copyright © 2011-2022 走看看