程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#利用反射方便取得DbDataReader裡的值

C#利用反射方便取得DbDataReader裡的值

編輯:C#入門知識

概述
在我以前做項目時,讀DbDataReder裡的值時都會用Reader.Read()然後根據名字來逐個讀出.自從學會利用反射來讀後,一切變得很容易.
以前的做法
定義一個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
}
 
然後讀取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;
    }
}
 
 
然後再如此讀出
/// <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;
}
 
 
利用反射後,一切變得很容易.
/// <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;
}
 
 
然後再這樣取出來
/// <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));
}
 
 
用好反射,讓Coding變得更容易。

 

摘自  spring yang 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved