码迷,mamicode.com
首页 > 其他好文 > 详细

【2016-11-2】【坚持学习】【Day17】【通过反射自动将datareader转为实体info】

时间:2016-11-02 23:22:16      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:and   rtu   esc   select   log   type   sum   dex   rac   

通过ADO.net 查询到数据库的数据后,通过DataReader转为对象Info

 

技术分享
 public class BaseInfo
    {
        /// <summary>
        /// 填充实体
        /// </summary>
        /// <param name="dr"></param>
        public virtual void Fill(DataRow dr)
        {
            PropertyInfo[] ps = this.GetType().GetProperties();

            foreach (PropertyInfo pinfo in ps)
            {
                if (dr.Table.Columns.Contains(pinfo.Name))
                {
                    pinfo.SetValue(this, dr[pinfo.Name], null);
                }
            }
        }
        /// <summary>
        /// 填充实体
        /// </summary>
        /// <param name="dr"></param>
        public virtual void Fill(DbDataReader dr)
        {
            PropertyInfo[] ps = this.GetType().GetProperties();

            foreach (PropertyInfo pinfo in ps)
            {
                int colIndex = dr.GetOrdinal(pinfo.Name);
                if (colIndex >= 0 && !dr.IsDBNull(colIndex))
                {
                    pinfo.SetValue(this, dr[pinfo.Name], null);
                }
            }
        }
    }
基类BaseInfo
技术分享
 public class BeaconDataInfo:BaseInfo
    {
        public string SeqNO { get; set; }
        public string CBID { get; set; }
        public string Time{ get; set; }
        public string DeviceName{ get; set; }
        public string FirmwareType{ get; set; }
        public string FirmwareVersion{ get; set; }
        public string LightIntensity{ get; set; }
        public string Major{ get; set; }
        public DateTime CreateTime { get; set; }

        public override void Fill(System.Data.Common.DbDataReader dr)
        {
            base.Fill(dr);
        }
    }
对象实体类
技术分享
 public List<BeaconReceiveInfo> Select()
        {
            string sql = "select * from BeaconReceive order by CreateTime desc limit 100 offset 0";

            using (DbDataReader dr = SqliteHelper.ExecuteReader(sql, SqliteHelper.ConnStr, null, System.Data.CommandType.Text))
            {
                List<BeaconReceiveInfo> lst = new List<BeaconReceiveInfo>();
                while (dr.Read())
                {
                    BeaconReceiveInfo info = new BeaconReceiveInfo();
                    info.Fill(dr);
                    lst.Add(info);
                }
                return lst;
            }
        }
业务查询方法

 

【2016-11-2】【坚持学习】【Day17】【通过反射自动将datareader转为实体info】

标签:and   rtu   esc   select   log   type   sum   dex   rac   

原文地址:http://www.cnblogs.com/zscmj/p/6024828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!