Code-Convert:将DataTable转成对象

ylbtech-Code-Convert:将DataTable转成对象
1.返回顶部
1、
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Sp.Common
{
    public class ConvertHelper
    {
        /// <summary>
        /// 将DataTable转成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableConvertToModel<T>(T model, DataTable dt) where T : class, new()
        {
            // 定义集合
            List<T> ts = new List<T>();
            // 获得此模型的类型
            Type type = typeof(T);
            string tempName = "";
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    // 检查DataTable是否包含此列
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter
                        if (!pi.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

    }
}
2、
2.返回顶部
 
3.返回顶部
 
4.返回顶部
 
5.返回顶部
 
 
6.返回顶部
 
warn 作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/storebook/p/12685037.html