【问题标题】:Type mismatch between columns in GET query. How to define returning column type when only NULL is returned?GET 查询中的列之间的类型不匹配。仅返回 NULL 时如何定义返回列类型?
【发布时间】:2021-10-13 12:14:18
【问题描述】:

我有一个现有的空数据表,其中包含 4 列 A、B、C、D:

DataTable dataTable = new DataTable
{
    Columns = 
    {
        new DataColumn("A", typeof(string)){ AllowDBNull = true },
        new DataColumn("B", typeof(string)){ AllowDBNull = true },
        new DataColumn("C", typeof(string)){ AllowDBNull = true },
        new DataColumn("D", typeof(string)){ AllowDBNull = true }
    }
} 

我想用数据库中的数据填充该表。数据库只包含 C 和 D 列,所以我想用 NULL 填充前 2 列。

所以我打电话:

await using DbConnection connection = new SqliteConnection("Data Source=MyDatabase.db");
await using DbCommand command = connection.CreateCommand();
string selectCommand = $"SELECT NULL as 'A', NULL as 'B', C, D FROM Table ";
command.CommandText = selectCommand;

await connection.OpenAsync().ConfigureAwait(false);
await using DbDataReader reader = await command.ExecuteReaderAsync().ConfigureAwait(false);
dataTable.Load(reader);
await connection.CloseAsync().ConfigureAwait(false);

一旦我到达那条线:

dataTable.Load(reader);

应用程序因异常而崩溃:

System.InvalidOperationException: 'Inconvertible type mismatch between SourceColumn 'A' of Byte[] and the DataColumn 'A' of String.'

是否可以修改代码,使返回的列'A'不是字节[]而是一个字符串。我尝试使用:

string selectCommand = $"SELECT CAST(NULL as TEXT) as 'A', CAST(NULL as TEXT) as 'B', C, D FROM Table ";

但它不起作用。它抛出相同的异常。 它在我使用空字符串而不是 NULLS 时有效,但我希望它们为 NULL 而无需任何额外的迭代工作。

【问题讨论】:

  • 您是否尝试不为 A 列和 B 列选择任何内容并将它们保留为默认值?
  • 另外,我认为您不应该将列 A 和 B 放在单引号内。它们应该是 A 和 B
  • 好的,当我不提及这些列时它可以工作。我不确定使用 A 而不是“A”。如果它不是'A',而是带有空格的文本'A AAA AAA'怎么办。不使用引号会破坏查询,我宁愿一直使用相同的编码风格。

标签: c# sqlite entity-framework entity-framework-core


【解决方案1】:

好的,史蒂夫给了我一个似乎可行的解决方案。 您只需要避免使用前 2 列:

string selectCommand = $"SELECT C, D FROM Table ";

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 2021-09-22
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2012-12-08
    • 1970-01-01
    相关资源
    最近更新 更多