/// <summary> /// 查询数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="param">sql参数,model or dictionary string object or IEnumerable<DbParameter> or IEnumerable<IDataParameter> </param> /// <param name="commandType"></param> /// <returns></returns> public virtual List <T> Query <T>(string sql, object param = null, CommandType?commandType = null) { this.CheckSql(sql); var t = typeof(T); bool isvalue = CheckModel(t); ReaderToModel ic = null; if (!isvalue && (t == typeof(string) || t.IsPrimitive && t.IsValueType)) { isvalue = true; } if (!isvalue && t.IsClass) { ic = ModelMaping.GetReaderToModel(t); } using (this.Open()) { using (IDbCommand command = this.Connection.CreateCommand()) { command.Connection = this.Connection; if (this.CommandTimeout.HasValue) { command.CommandTimeout = this.CommandTimeout.Value; } if (commandType.HasValue) { command.CommandType = commandType.Value; } if (this.transaction != null) { command.Transaction = this.transaction; } AddParam(command, sql, param); WriteLog(command); using (var reader = command.ExecuteReader()) { var list = new List <T>(); while (reader.Read()) { object o = default(T); if (ic != null) { o = ic.To(reader); } else { var v = reader.GetValue(0); o = ChangeType(v, t) ?? default(T); } list.Add((T)o); } return(list); } } } }
public static List <T> Query <T>(this IDatabase db, string sql, object parameters = null, CommandType?commandType = null) { db.Check(sql); var t = typeof(T); bool isvalue = CheckModel(t); var list = new List <T>(); ReaderToModel ic = null; if (!isvalue && (t == typeof(string) || t.IsPrimitive && t.IsValueType)) { isvalue = true; } if (!isvalue && t.IsClass) { ic = GetReaderToModel(t); } AddParam(db, sql, parameters, commandType); using (var reader = db.ExecuteReader()) { while (reader.Read()) { object o = default(T); if (ic != null) { o = ic.To(reader); } else { var v = reader.GetValue(0); o = ChangeType(v, t) ?? default(T); } list.Add((T)o); } } return(list); }