无法使用SqlDataReader.GetColumnSchema()

时间:2019-04-05 07:50:09

标签: c# database sqldatareader

我正在尝试使用SqlDataReader类的GetColumnSchema方法。但是VS告诉我SqlDataReader不包含GetColumnSchema的定义。我会错过名称空间或程序集引用吗?

我的项目正在使用.NET Framework 4.6.1

using System;
using DocuWare.LoggingNew;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Linq;
using System.Linq;
using System.IO;

private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile)
{
  StreamWriter outputFile = new StreamWriter(dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile);           

  using (SqlConnection sqlCon = new SqlConnection("Data Source=" + GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
    {
      SqlCommand command = new SqlCommand(sqlQuery, sqlCon);
      sqlCon.Open();
      SqlDataReader reader = command.ExecuteReader();
    try
    {   
        while (reader.Read())
        {
            var columnSchema = reader.GetColumnSchema();
            string header = string.Empty;

            for (int i = 0; i < reader.FieldCount; i++)
            {
                header += $", {columnSchema[i].ColumnName}";
            }
        }
    }
    catch (Exception ex)
    {
        logger.Debug(ex, "Writing Database Output to the " + nameOfOutputFile + " file failed");
    }
    finally
    {
        reader.Close();
        outputFile.Close();
        sqlCon.Close();
    }
}

}

1 个答案:

答案 0 :(得分:0)

SqlDataReader具有属性GetName(),该属性接受索引并返回列名。

GetName()在大多数.Net框架(从v1.1起)和.Net核心(从v1.0起)版本中受支持。

while (reader.Read())
{
    string header = string.Empty;

    for (int i = 0; i < reader.FieldCount; i++)
    {
        header += $", {reader.GetName(i)}";
    }
}

或者您可以使用方法链接和Linq来做到这一点:

// returns List<string>
var columns = Enumerable.Range(0, reader.FieldCount)
                        .Select(reader.GetName)
                        .ToList();

// columns joined on ", "
var header = string.Join(", ", columns);