如何将 "NULL/DbNull" 发送到数据类型为 table 的列中:可为 nullable int

How to send in "NULL/DbNull" into a table-column with the datatype: nullable int

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

我有一个文本框,当它留空时应该将 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?,现在有一种方法可以确定如何计算条件表达式。

有一个 DBNull class 的单例实例。尝试分配 DBNull.Value