zoukankan      html  css  js  c++  java
  • 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;
            //}
        }
  • 相关阅读:
    超简单实例使用websocket进行server和client实时通信
    antd的table行key自增长
    selenium元素定位Xpath,Contains,CssSelector
    slenium使用鼠标+键盘事件或者双击实现代码
    使用python+pychram进行API测试(接口测试)初级STEP 1
    linux命令小常识
    sql中limit使用方法
    Swagger-API测试工具实战
    写 test-case心得
    测试之路之[前奏]
  • 原文地址:https://www.cnblogs.com/zhangchaoran/p/8513430.html
Copyright © 2011-2022 走看看