Saturday, February 25, 2012

ADO.NET, SqlParameter, and NULL

Im trying to execute the following:

mySqlCmd.Parameters.Add("@.Parent_ID", SqlDbType.Int).Value = (sectionUpdate.iSection.ParentID == 0 ? DBNull.Value : myParentID);

However i get an error that Null cant be converted to Int. Is there any way i can uyse the SqlParameters approach but pass in a Null value for the field or must i wrap the entire connection within a IF/ELSE statement one containing a hard-coded NULL within the query and the other as a standard parameter with a proper int value?


Thanks

I found a solution:

SqlParameter sp = mySqlCmd.Parameters.Add("@.ParentID", SqlDbType.Int);
sp.IsNullable = true;

if (sectionUpdate.iSection.ParentID == 0)
sp.Value = DBNull.Value;
else
sp.Value = sectionUpdate.iSection.ParentID;

No comments:

Post a Comment