Convert dbnull to string. Record dbnull.value in database instead of Nothing

一世执手 提交于 2019-12-24 07:26:29

问题


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.


回答1:


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

Dim oErrorDate2 as Object = System.DbNull.Value

If strErrorDate2 <> Nothing Then oErrorDate = strErrorDate2

.Add(New SqlParameter("@ErrorDate2",oErrorDate2))



回答2:


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.



来源:https://stackoverflow.com/questions/13864696/convert-dbnull-to-string-record-dbnull-value-in-database-instead-of-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!