C # using reflection of the value in convenient access to DbDataReader

Outline

When I was doing the project before, during DbDataReder in value will be read by Reader.Read () and then read out one by one by name. Since reflection to learn to use reading, everything becomes very easy.

Previous practice

The definition of an Entity

    public class FileInformationModel  
    {
        #region Public Property

        /// <summary>
        /// Gets and sets the file ID
        /// </summary>
        public string FileID { get; set; }

        /// <summary>
        /// Gets and sets the file name
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Gets and sets the file save type
        /// </summary>
        public int? FileSaveType { get; set; }

        /// <summary>
        /// Gets and sets the file url
        /// </summary>
        public string FileUrl { get; set; }

        /// <summary>
        /// Gets and sets the file is new 
        /// </summary>
        public bool? IsNew { get; set; }

        /// <summary>
        /// Gets and sets the file last access time
        /// </summary>
        public DateTime? LastAccessTime { get; set; }

        /// <summary>
        /// Gets and sets the file modity time
        /// </summary>
        public DateTime? ModifyTime { get; set; }

        /// <summary>
        /// Gets and sets the file version
        /// </summary>
        public int? Version { get; set; }

        /// <summary>
        /// Gets and sets the file content owner
        /// </summary>
        public string ContentOwner { get; set; }

        /// <summary>
        /// Gets and sets the file content type
        /// </summary>
        public string ContentType { get; set; }

        /// <summary>
        /// Gets and sets the file create date time
        /// </summary>
        public DateTime? CreateTime { get; set; }

        /// <summary>
        /// Gets and sets the file access control
        /// </summary>
        public string FileAccessControl { get; set; }

        /// <summary>
        /// Gets and sets the file from
        /// </summary>
        public string FileFrom { get; set; }

        #endregion
    }

 

Then read DbDataReader

 

        /// <summary>
        /// Execute reader by store procedure and parameter list
        /// </summary>
        /// <param name="cmdText">store procedure</param>
        /// <param name="parameters">parameter list</param>
        /// <returns>data reader</returns>
        public DbDataReader ExecuteReader(string cmdText, List<DbParameter> parameters,out DbConnection conn)
        {
            lock (lockObject)
            {
                  conn = new MySqlConnection(ConnectionString);
                MySqlCommand command = new MySqlCommand();
                PrepareCommand(command, conn, cmdText, parameters);
                MySqlDataReader mySqlDataReader = command.ExecuteReader();
                return mySqlDataReader;
            }
        }

 

 

So then read data

        /// <summary>
        /// Query FileInformationModel entity list by FileInformationModel entity
        /// </summary>
        /// <param name="entity">FileInformationModel entity</param>
        /// <returns>FileInformationModel entity list</returns>
        public List<FileInformationModel> Query(FileInformationModel entity)
        {
           DbConnection conn;
            var result =
                ConvertDataReaderToList(DBHelp.ExecuteReader(Constants.spSelectFileInformationByCondition,
                                                             GetParameters(entity),out conn));
           ContentHelp.CloseConnection(conn);
           return result;
        }

        /// <summary>
        /// Convert data reader to FileInformationModel entity list
        /// </summary>
        /// <param name="reader">Db DataReader</param>
        /// <returns>FileInformationModel entity list</returns>
        private List<FileInformationModel> ConvertDataReaderToList(DbDataReader reader)
        {
            List<FileInformationModel> fileInformationList = new List<FileInformationModel>();
            using (reader)
            {
                while (reader.Read())
                {
                    FileInformationModel entity = new FileInformationModel();
                    entity.ContentType = ContentHelp.GetObjectToString(reader["ConntentType"]);
                    entity.ContentOwner = ContentHelp.GetObjectToString(reader["ContentOwner"]);
                    entity.CreateTime = ContentHelp.GetObjectToDateTime(reader["CreateTime"]);
                    entity.FileAccessControl = ContentHelp.GetObjectToString(reader["FileAccessControl"]);
                    entity.FileFrom = ContentHelp.GetObjectToString(reader["FileFrom"]);
                    if (ContentHelp.GetObjectToString(reader["IsNew"]) != null)
                        entity.IsNew = Convert.ToBoolean(ContentHelp.GetObjectToInt(reader["IsNew"]));
                    entity.FileName = ContentHelp.GetObjectToString(reader["FileName"]);
                    entity.FileSaveType = ContentHelp.GetObjectToInt(reader["FileSaveType"]);
                    entity.FileUrl = ContentHelp.GetObjectToString(reader["FileUrl"]);
                    entity.FileID = ContentHelp.GetObjectToString(reader["FileID"]);
                    entity.LastAccessTime = ContentHelp.GetObjectToDateTime(reader["LastAccessTime"]);
                    entity.ModifyTime = ContentHelp.GetObjectToDateTime(reader["ModifyTime"]);
                    entity.Version = ContentHelp.GetObjectToInt(reader["Version"]);
                    fileInformationList.Add(entity);
                }
            }
            return fileInformationList;
        }

 

 

After using reflection, everything becomes very easy.

        /// <summary>
        /// Execute reader by store procedure and parameter list
        /// </summary>
        /// <param name="cmdText">store procedure</param>
        /// <param name="parameters">parameter list</param>
        /// <returns>data reader</returns> 
        public List<T> ReadEntityList<T>(string cmdText, List<DbParameter> parameters) where T : new()
        {
            lock (lockObject)
            {
                using (MySqlConnection conn = new MySqlConnection(ConnectionString))
                {
                    using (MySqlCommand command = new MySqlCommand())
                    {
                        PrepareCommand(command, conn, cmdText, parameters);
                        MySqlDataReader mySqlDataReader = command.ExecuteReader();
                        return ReadEntityListByReader<T>(mySqlDataReader);
                    }
                }
            }
        }

        /// <summary>
        /// Read entity list by reader
        /// </summary>
        /// <typeparam name="T">entity</typeparam>
        /// <param name="reader">data reader</param>
        /// <returns>entity</returns>
        private List<T> ReadEntityListByReader<T>(MySqlDataReader reader) where T : new()
        {
            List<T> listT = new List<T>();
            using (reader)
            {
                while (reader.Read())
                {
                    T inst = new T();
                    foreach (var pi in typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
                    {
                        var obj = new object();
                        try
                        {
                            obj = reader[pi.Name];
                        }
                        catch (Exception ex)
                        {
                            continue;
                        }

                        if (obj == DBNull.Value || obj == null)
                            continue;
                        var si = pi.GetSetMethod();
                        if (si == null)
                            continue;
                        pi.SetValue(inst, obj, null);
                    }
                    listT.Add(inst);
                }
            }
            return listT;
        }

 

 

Thus taken out and then

        /// <summary>
        /// Query FileInformationModel entity list by FileInformationModel entity
        /// </summary>
        /// <param name="entity">FileInformationModel entity</param>
        /// <returns>FileInformationModel entity list</returns>
        public List<FileInformationModel> Query(FileInformationModel entity)
        {
            return DBHelp.ReadEntityList<FileInformationModel>(Constants.spSelectFileInformationByCondition,
                                                               GetParameters(entity));
        }

 

 

Good use of reflection, let Coding easier.

Welcome you to participate in the discussion, if you feel you have help, click on     the recommendation, thank you very much.image

Author: the Spring Yang

Source: http://www.cnblogs.com/springyangwc/

This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise the right to pursue legal responsibilities.

Reproduced in: https: //www.cnblogs.com/springyangwc/archive/2012/03/31/2427533.html

Guess you like

Origin blog.csdn.net/weixin_33994444/article/details/93340968