我有一个现有的空DataTable,其中包含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‘不是byte[],而是一个字符串。我尝试使用:
string selectCommand = $"SELECT CAST(NULL as TEXT) as 'A', CAST(NULL as TEXT) as 'B', C, D FROM Table ";
但它不起作用。它会抛出同样的异常。当我使用空字符串而不是NULL时,它可以工作,但我希望它们是NULL,而不需要任何额外的迭代工作。
发布于 2021-08-09 12:54:18
好吧,史蒂夫给了我一个似乎有效的解决方案。你只需要避免使用前两列:
string selectCommand = $"SELECT C, D FROM Table ";
https://stackoverflow.com/questions/68718206
复制相似问题