0

I have a column with SQL type of smallint (EF type of Int16) that I want to insert a null value into but when I use the below code I get the error that null can not be converted to short. How can I get this one line if statment to allow me to insert a null?

CollectionID = (ddlCollection.SelectedValue == "None") ? null  : Convert.ToInt16(ddlCollection.SelectedValue)

4 Answers4

2

Working code is to do a nullablecnvert like:

CollectionID = (ddlCollection.SelectedValue == "None") ? (Nullable<Int16>)null : Convert.ToInt16(ddlCollection.SelectedValue)
1

c# has a values for null in database: DBNull.Value

Goran Štuc
  • 581
  • 4
  • 15
0

The first problem is that your Entity Framework property CollectionID must be marked as Nullable (if you're using EDMX) or declared as short? or Nullable<short> if you're using Code First.

Secondly, you need to make sure the database type for that column is also marked as nullable (something like smallint NULL in SQL Server).

EDIT: Ah, I think I see the problem now. Try casting your call to Convert.ToInt16 to Nullable<short>. The ternary operator sees a null on the true side, and type incompatible with the null value on the false side, which is causing your error.

CollectionID = (ddlCollection.SelectedValue == "None")
    ? (Nullable<short>)null 
    : (Nullable<short>)Convert.ToInt16(ddlCollection.SelectedValue)
Adam Maras
  • 26,269
  • 6
  • 65
  • 91
  • Everthing is setup as nullable in EF and SQL. The problem is happening way before I even hit the DB. I can not build since VS2012 is throwing the error listed in first post. –  Dec 01 '12 at 19:50
  • Your edit is equivalant to my current code, the error is thrown on the null varable not the ddlCollection. The goal is that if None is selected in the drop down to insert null otherwise insert the selectedvalue. –  Dec 01 '12 at 19:59
  • I edited my answer once more. The first branch of the conditional operator is what dictates the return type of the expression, so the `null` must be casted to `Nullable` for the whole thing to work. – Adam Maras Dec 01 '12 at 20:11
0

Use it with sqlcommand parameter

 if(ddl_collection.selectedvalue!="None")
   command.Parameters.AddWithValue("@CollectionID", Convert.ToInt16(ddlcollection.selectedValue));
else
    command.Parameters.AddWithValue("@CollectionID", DBNull.Value);
Niloofar
  • 723
  • 8
  • 9