using System; using System.Data; using System.Reflection; using System.Data.Common; using System.Data.SqlClient; using System.Collections.Generic; namespace DataReaderList { public partial class ReaderList { /// /// 读取实体列表 /// ///要读取的实体 ///数据源 ///成功(实体列表)/失败(Null) public static IList ReadEntityListByReader(DbDataReader reader) where T : new() { IList ilist = null; try { ilist = new List(); using (reader) { while (reader.Read()) { T model = new T(); foreach (var item in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var obj = new object(); try { obj = reader[item.Name]; } catch (Exception ex) { continue; } if (obj == DBNull.Value || obj == null) continue; var value = item.GetSetMethod(); if (value == null) continue; item.SetValue(model, obj, null); } ilist.Add(model); model = default(T); } } return ilist; } finally { ilist = null; } } /// /// 读取实体 /// ///要读取的实体 ///数据源 ///成功(实体列表)/失败(Null) public static T ReadEntityByReader(DbDataReader reader) where T : new() { T model = default(T); try { using (reader) { if (reader.Read()) { model = new T(); foreach (var item in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var obj = new object(); try { obj = reader[item.Name]; } catch (Exception ex) { continue; } if (obj == DBNull.Value || obj == null) continue; var value = item.GetSetMethod(); if (value == null) continue; item.SetValue(model, obj, null); } } } return model; } finally { model = default(T); } } /// /// 读取实体列表 /// ///要读取的实体 ///执行数据语句 ///语句参数 ///成功(实体列表)/失败(Null) public static IList ReadEntityList(string cmdText, DbParameter[] parameters) where T : new() { using (SqlConnection conn = new SqlConnection("")) { using (SqlCommand cmd = new SqlCommand()) { PrepareCommand(cmd, conn, cmdText, parameters); SqlDataReader sdr = cmd.ExecuteReader(); return ReadEntityListByReader(sdr); } } } /// /// 执行语句参数设置 /// ///执行数据命令 ///数据连接 ///执行数据语句 ///语句参数 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, string cmdText, DbParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } } }