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


    概述

    在我以前做项目时,读DbDataReder里的值时都会用Reader.Read()然后根据名字来逐个读出.自从学会利用反射来读后,一切变得很容易.

    以前的做法

    定义一个Entity

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /// <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;
        }
    }

    然后再如此读出数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    /// <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;
    }

    利用反射后,一切变得很容易.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    /// <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;
    }

    然后再这样取出来

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /// <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

    出处:http://www.cnblogs.com/springyangwc/

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    转发:招聘一个靠谱的 iOS
    转发:经典面试题
    APP上架证书无效:解决
    转发:Xcode插件
    Alcatraz:插件管理
    类似禅道的多条件搜索功能,比如或者并且和模糊查询和指定查询,见下图吧
    关于angularjs中,数据模型被改变,页面不刷新的解决办法
    angluar1+ionic详情页返回在原来的位置(缓存数据和页面高度)
    unable to resolve module react-native-gesture-handler from
    解决React Native:Error: Cannot find module 'asap/raw'
  • 原文地址:https://www.cnblogs.com/jzjblog/p/2653881.html
Copyright © 2020-2023  润新知