对于所有其他数据类型,它都可以正常工作,但我无法使其与“bit”列一起正常工作。
这是我用于批量写入的SQL:
using (var bulk = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity & SqlBulkCopyOptions.KeepNulls))
{
bulk.BatchSize = 2000;
bulk.DestinationTableName = targetTable;
bulk.WriteToServer(dataTable);
}
这是我的数据表格:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("MyBool", typeof(bool)); // Tried with and without typeof(bool)
return dt;
这是我在添加到datatable之前构建行的方法。 personAssociationRow["MyBool"] = true;
异常是在WriteToServer行上抛出的,取决于是否指定了typeof(bool):
当值为true时,会显示"Cannot insert the value NULL into column 'MyBool', table",但是智能感知/调试器将其显示为true;
当值为"True"字符串时,会显示"The given value of type String from the data source cannot be converted to type int of the specified target column."。
在数据库中,该列被定义为bit类型且不允许为空值。
有什么想法可以解决这个布尔值问题吗?
编辑:刚找到并尝试过SqlBoolean作为类型,但它没有起作用,显示为"The given value of type SqlBoolean from the data source cannot be converted to type int of the specified target column.",这表明int应该可以工作,但事实并非如此。
编辑:我怀疑问题在于它认为底层数据库的类型是int,而实际上类型为bit,因此错误消息说明无法转换为底层类型int。
int
数据类型,将0
用作false
的值,将1
用作true
的值,而不是使用bool
。 - Andrey Gordeev