Skip to main content
 首页 » 编程设计

c#之如何将 "NULL/DbNull"发送到数据类型为 : nullable int 的表列中

2024年02月06日24xing901022

我在 sql-server 2012 中得到了一个表,其中一列的数据类型为 int 但也可以为 null。

我有一个文本框,当它留空时,应该将 NULL 插入到可为 null 的 int 单元格中。但是我在发送什么类型以翻译为 null 时遇到了问题。我想要的是 int 数据类型,但也需要 null(int?)发送到数据库中。

var tbl_row = db.table.Where(n => n.key.Equals(key)).SingleOrDefault(); 
 
tbl_row.nullable_int = this.tb.Text == "" ? [null int value] : int.Parse(this.tb.Text); 

请您参考如下方法:

你应该写:

tbl_row.nullable_int = this.tb.Text == "" ? (int?)null : int.Parse(this.tb.Text); 

为了使条件运算符表达式有效。

根据 the documentation :

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

在你的例子中,null 和一个计算为 int 的表达式混淆了编译器。通过将第一个表达式显式转换为 int?,它现在有一种方法可以确定如何计算条件表达式。