I have a null value in my database which gives me an error if I try perform any mathematical operations on it. I tried putting this in my controller action:
If String.IsNullOrEmpty(item.Tbl_Food.Fiber_TD_g) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
This my model for the field:
Public Property Fiber_TD_g() As Nullable(Of Double)
However, it says “Nullable object must have a value.” on the If String.IsNullOrEmpty(item.Tbl_Food.Fiber_TD_g) Then line. How can I check if the “string” (it’s a double, not a string) is empty and default it to zero, properly?
Edit:
I tried a suggestion below, and I no longer get an error in my controller, but instead in my View. It says, “Nullable object must have a value.” on the line FiberTotal += item.Tbl_Food.Fiber_TD_g in my view.
Dim food = db.Tbl_Food_Logs.Where(Function(x) x.FLog_Employee_ID = empId And x.FLog_Created_Date >= date2 And x.FLog_Created_Date < tomorrow)
For Each item In food
If IsDBNull(item.Tbl_Food.Fiber_TD_g) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
Next
Return View(food)
As its name implies,
String.IsNullOrEmptyis a string operation. It won’t work if you pass adouble. Instead check to see if itIs Nothing:This operation is common enough that VB has a shortcut, called the null coalescing operator (2-argument
If):When
Ifhas two arguments, it returns the first argument if it’s not null and the second if it is.