将 DataRow 项设置为 null
我有一个文本文件,我将其读入数据表,然后执行批量插入到 SQL Server 表中。它非常快,并且当所有导入的值都被视为字符串(日期、字符串、整数等都导入到字符串字段中)时效果很好。
现在我已经弄清楚了这个概念,我将返回在数据库和代码中分配真实的数据类型。数据库为字段分配了正确的类型。我现在正在编写代码。
我的日期有问题。正如我所提到的,一切都是字符串并被转换为正确的类型。在下面的代码中,我想测试表示日期的字符串值是否为空或空格。如果不为空,则使用现有值。否则,将其设置为空。
row[i] = !string.IsNullOrWhiteSpace(data[i]) ? data[i] : DBNull.Value;
我尝试使用 null
但收到错误消息,告诉我改用 DBNull
。当我使用 DBNull 时,我收到一条消息,告诉我字符串和 System.DBNull 之间没有隐式转换。
数据表中的列已指定数据类型(在本例中为 DataType = Type.GetType("System.DateTime")
),并且我为此列设置了 AllowDBNull = true
如何我能处理这个吗?
谢谢!
I have a text file that I read into a data table and then perform a bulk insert into a SQL Server table. It's quite fast and it works great when all the imported values are treated as strings (dates, strings, ints, etc are all imported into string fields).
Now that I have the concept worked out, I'm going back to assign real datatypes in the database and my code. The database has the correct types assigned to the fields. I'm working on the code now.
I'm having a problem with dates. As I mentioned, everything is a string and gets converted to the correct type. In the following code, I want to test if the string value representing a date is null or whitespace. If it isn't null, then use the existing value. Otherwise, set it to null.
row[i] = !string.IsNullOrWhiteSpace(data[i]) ? data[i] : DBNull.Value;
I tried using null
but get an error telling me to use DBNull
instead. When I use DBNull
, I get a message telling me there is no implicit conversion between string and System.DBNull
.
The columns in the datatable have datatypes specified (in this case, DataType = Type.GetType("System.DateTime")
) and I set AllowDBNull = true
for this column
How do I handle this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是由于您正在使用的操作造成的。由于
DBNull.Value
不是字符串,因此无法使用条件运算符。这是因为,根据条件运算符文档:尝试这样做:
这绕过了双方相同的转换要求。或者,您可以将两者显式转换为
System.Object
,并仍然使用条件运算符。The problem is because of the operation you are using. Since
DBNull.Value
is not a string, you can't use the conditional operator. This is because, from the conditional operator docs:Try doing this:
This bypasses the conversion requirements for both sides to be the same. Alternatively, you can cast both to a
System.Object
explicitly, and still use the conditional operator.您需要将它们都转换为对象,如下所示:
You need to cast them both to objects like so:
我正在开发 Asp.Net MVC 5 C# Web 应用程序,并且这样做并且工作正常
I'm working on Asp.Net MVC 5 C# Web Application and did like this and working fine
如果只想检查 NULL,也可以使用以下语法:
If you only want to check NULLs, you can also use this syntax: