1

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);

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

12 Comments

May I suggest the use of string.IsNullOrWhiteSpace(this.tb.Text) instead of this.tb.Text == ""
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
Oh, OK then. Thank you very much @GrantWinney for the warning. But still " " will pass the condition test but fail int.Parse() and will throw Exception.
Just make sure that tbl_row.nullable_int property is indeed of type Nullable<int>
Nevermind my earlier comment. This works, I was trying to cast int? on a not nullable column.
|
0

There is a singleton instance of a DBNull class. Try assingning DBNull.Value

4 Comments

Already tried that: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'int'.
tbl_row.nullable_int = this.tb.Text == "" ? (object)DBNull.Value : (object)int.Parse(this.tb.Text); The ? operator requires both of its returning arguments to be of the same type or to be implicitly convertible.
Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)
never mind see w0lf's answer, I didn't see that you're using EF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.