コード例 #1
0
        /// <summary>
        /// Retrieves a row of data from a table.
        /// </summary>
        /// <param name="tableName">The table name.</param>
        /// <param name="keyValue">The key value.</param>
        /// <param name="columnNames">The columns you want returned (null means ALL).</param>
        /// <param name="keyColumnName">Name of the key column (usually the primary key).</param>
        public DbTestTableData Retrieve(string tableName, object keyValue, IEnumerable <string> columnNames = null, string keyColumnName = null)
        {
            const string SelectTemplate = "select {0} from dbo.{1} where {2} = {3}";

            var tableData = new DbTestTableData(tableName);

            if (keyColumnName == null)
            {
                keyColumnName = tableName.Substring(0, tableName.Length - 2) + "Id";
            }

            var columns         = columnNames == null ? "*" : string.Join(",", columnNames);
            var selectStatement = string.Format(SelectTemplate, columns, tableName, keyColumnName, keyValue);

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                var cmd    = new SqlCommand(selectStatement, connection);
                var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    tableData.AddRange(
                        Enumerable.Range(0, reader.FieldCount)
                        .Select(i => new DbTestColumnData <object>(reader.GetName(i), reader[i])));
                }

                reader.Close();
            }

            return(tableData);
        }