Reputation: 1900
I got a table in sql-server 2012 with a column that is the datatype int but also nullable.
I've a textbox that when left empty should insert NULL
into the nullable int cell. But I'm having trouble with what type to send in to be translated as null
. What I want is a datatype of int but also null (int?) to send into the database.
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);
Upvotes: 1
Views: 1757
Reputation: 15797
There is a singleton instance of a DBNull class. Try assingning DBNull.Value
Upvotes: 0
Reputation: 40516
You should write:
tbl_row.nullable_int = this.tb.Text == "" ? (int?)null : int.Parse(this.tb.Text);
for the conditional operator expression to be valid.
According to 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.
In your case, null
and an expression evaluated as an int
confused the compiler. By explicitly casting the first expression to int?
, there is now a way for it to figure out how to evaluate the conditional expression.
Upvotes: 5