• DataSet结果转模型类


    引入命名空间:

    using System.Data;
    using System.Reflection;

    类封装代码:

        public class ModelHelper
        {
            public T To<T>(DataRow dr) where T : new()
            {
                T model= new T();                   //T model = default(T); //model = Activator.CreateInstance<T>();
                Type t = model.GetType();                       //获取模型类的类型
    
                //循环遍历模型类的每一个属性,并为其赋值
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    if (dr.Table.Columns.Contains(pi.Name))           //如果DataTable的列中包含当前的属性名
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[pi.Name];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(model, value, null);
                        }
                        else
                        {
                            pi.SetValue(model, null, null);
                        }
                    }
    
                }
    
                return model;
            }
    
            public IList<T> ToList<T>(DataTable dt) where T : new()
            {
                List<T> list = new List<T>();
                foreach (DataRow dr in dt.Rows)
                {
                    list.Add(To<T>(dr));
                }
                return list;
            }
    
    
            //另一种写法
            //public T To<T>(DataTable dt) where T : new()
            //{
            //    T model = default(T);
            //    model = Activator.CreateInstance<T>();
    
            //    PropertyInfo[] propertys = model.GetType().GetProperties();         //获取模型类的类型
    
            //    //循环遍历模型类的每一个属性,并为其赋值
            //    foreach (PropertyInfo pi in propertys)
            //    {
            //        if (dt.Columns.Contains(pi.Name))           //如果DataTable的列中包含当前的属性名
            //        {
            //            if (!pi.CanWrite) continue;
            //            object value = dt.Rows[0][pi.Name];
            //            if (value != DBNull.Value)
            //            {
            //                pi.SetValue(model, value, null);
            //            }
            //            else
            //            {
            //                pi.SetValue(model, null, null);
            //            }
            //        }
            //    }
    
            //    return model;
            //}
        }
  • 相关阅读:
    单行居中,2行居左,超过2行省略
    Angular2环境搭建
    数字保留2位小数
    结束循环函数
    获取元素的定位值
    $.extend
    node使用指南
    Telsa显卡比较
    Jupyter-notebook 不自动打开浏览器解决办法
    teamviewer连接未就绪的解决(Manjaro Linux)
  • 原文地址:https://www.cnblogs.com/zhangchaoran/p/8513430.html
Copyright © 2020-2023  润新知