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

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

通过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】