I have an insertRecord function in vb.net that uses a parameter query. If there is no error date given, I need to insert dbnull.value into the db instead of ""(Nothing).
Dim strErrorDate2 As DateTime = Request.Form("dateOfErrorDatePicker2").ToString
.Add(New SqlParameter("@ErrorDate2", If(strErrorDate2 <> Nothing, strErrorDate2.Date, DBNull.Value)))
I keep getting conversion errors on dbnull to string. Originally it had it's own if/else block where I initialized the variable, but I couldn't figure out how to convert it correctly. I tried the inline if, but I still need to do a conversion or try something else.
Any ideas? The problem is that when I insert an empty string or DateTime into the database it records as a min possible date such as 1/1/1900.
EDIT: "Cannot infer a common type, 'object' assumed." That's the error I'm currently getting.
It's because strErrorDate2.Date is a DateTime and System.DbNull.Value is an object. Either Direct Cast strErrorDate2 to object in the IF() or do something like this
This is almost certainly happening because of what is on your SQL Server side. It is very likely that either you are calling a stored procedure that is replacing the Null with a minimum date, or else (more likely) the table that you are inserting into has either a Trigger or a Default column value that is assigning a minimum date when it is Null.
Just to clarify: First, you shouldn't have to worry about turning Nothing into DBNulls, ADO.net should be doing that for you.
Secondly, if you send SQL Server Nothing/Null and it stores something else, then that's because it (the table or the stored procedure) is replacing the NULL with a default value. This is most likely because the data design does not want NULLs to be in the column that you are trying to insert them to.