【发布时间】: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