【问题标题】:Fetch rows from database using ExecuteStoreQuery, without knowing the number of columns in the table使用 ExecuteStoreQuery 从数据库中获取行,而不知道表中的列数
【发布时间】:2013-03-01 15:48:53
【问题描述】:

我正在尝试使用 ObjectContext 上的 ExecuteStoreQuery 方法对我的 SQLite 数据库执行一些手动 SQL 查询。

问题是我并不总是知道我正在查询的表中有多少列。理想情况下,我希望每个提取的行都只是一个 string[] 对象。

我在这里查看了示例 2:http://msdn.microsoft.com/en-us/library/vstudio/dd487208(v=vs.100).aspx

这与我想要做的很接近,只是我不知道我正在获取的TElement 的结构,所以我无法像示例中那样定义结构。

以下是我的一些代码(由于???? TElement 而无法编译)。下面的代码试图获取表信息,所以在这种情况下,我确实知道行的结构,但通常我不知道。

有没有办法用ExecuteStoreQuery 做到这一点?还是有不同的方法,同时仍然使用我的ObjectContext 的现有连接(而不是打开到数据库的新 SQL 连接)?

public void PrintColumnHeaders(NWRevalDatabaseEntities entities, string tableName)
{
    string columnListQuery = string.Format("PRAGMA table_info({0})", tableName);

    var result = entities.ExecuteStoreQuery<????>(columnListQuery);

    foreach (string[] row in result)
    {
        string columnHeader = row[1]; // Column header is in second column of table
        Console.WriteLine("Column Header: {0}", columnHeader);
    }
}

【问题讨论】:

  • 我认为这需要较低级别的方法:针对存储连接发出命令(返回 object[])。
  • @GertArnold 谢谢,感谢您,我得到了这个工作。您想发布答案以便我接受吗?
  • 你做了所有的工作!我建议您将 UPDATE 移至答案并标记它。
  • 你太客气了:-)我明天解锁后接受。

标签: c# database entity-framework sqlite executestorequery


【解决方案1】:

我根据 Gert Arnold 的评论完成了这项工作。此外,我花了一些功夫才发现我需要一个 SQLiteConnection,而不是我可以直接从 ObjectContext 获得的 EntityConnection。 this 问题的答案帮助了我。

工作代码如下:

public static void PrintColumnHeaders(NWRevalDatabaseEntities entities, string tableName)
{
    var sc = ((System.Data.EntityClient.EntityConnection)entities.Connection).StoreConnection;
    System.Data.SQLite.SQLiteConnection sqliteConnection = (System.Data.SQLite.SQLiteConnection)sc;

    sqliteConnection.Open();
    System.Data.Common.DbCommand cmd = sc.CreateCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = string.Format("PRAGMA table_info('{0}');", tableName);
    System.Data.Common.DbDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
        object[] values = new object[reader.FieldCount];
        while (reader.Read())
        {
            int result = reader.GetValues(values);
            string columnHeader = (string)values[1]; // table_info returns a row for each column, with the column header in the second column.
            Console.WriteLine("Column Header: {0}", columnHeader);
        }
    }
    sqliteConnection.Close();
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多