我有这个WebInvoke方法:
<OperationContract()>
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)>
Public Function Actions_Update_ByID(ByVal aID As Int32, Optional aActionID As Int32 = Nothing, Optional aConsequence_Paid As Boolean = Nothing, Optional aDate As DateTime = Nothing, Optional aName As String = Nothing, Optional aNotes As String = Nothing, Optional aReward_Paid As Boolean = Nothing) As String
Try
Dim c As New Common
Dim ps As SqlParameter() = {New SqlParameter("@ID", SqlDbType.Int), New SqlParameter("@ActionID", SqlDbType.Int), New SqlParameter("@Consequence_Paid", SqlDbType.Bit), New SqlParameter("@Date", SqlDbType.DateTime), New SqlParameter("@Name", SqlDbType.NVarChar), New SqlParameter("@Notes", SqlDbType.NVarChar), New SqlParameter("@Reward_Paid", SqlDbType.Bit)}
ps(0).Value = aID
ps(1).Value = IIf(aActionID = Nothing, DBNull.Value, aActionID)
ps(2).Value = IIf(aConsequence_Paid = Nothing, DBNull.Value, aConsequence_Paid)
ps(3).Value = IIf(aDate = Nothing, DBNull.Value, aDate)
ps(4).Value = IIf(aName = Nothing, DBNull.Value, aName)
ps(5).Value = IIf(aNotes = Nothing, DBNull.Value, aNotes)
ps(6).Value = IIf(aReward_Paid = Nothing, DBNull.Value, aReward_Paid)
c.ExecuteSQLCommand("UPDATE [Actions] SET [ActionID] = @ActionID,[Consequence_Paid] = @Consequence_Paid,[Date] = @Date,[Name] = @Name,[Notes] = @Notes,[Reward_Paid] = @Reward_Paid WHERE [ID] = @ID", ps)
Return (New JavaScriptSerializer()).Serialize(String.Empty)
Catch ex As Exception
Dim row As New Dictionary(Of String, String) From {{"error", ex.Message}}
Return (New JavaScriptSerializer()).Serialize(row)
End Try
End Function
所有参数都传递给此方法,sql查询的跟踪是:
exec sp_executesql N'UPDATE [Actions] SET [ActionID] = @ActionID,[Consequence_Paid] = @Consequence_Paid,[Date] = @Date,[Name] = @Name,[Notes] = @Notes,[Reward_Paid] = @Reward_Paid WHERE [ID] = @ID',N'@ID int,@ActionID int,@Consequence_Paid bit,@Date datetime,@Name nvarchar(9),@Notes nvarchar(30),@Reward_Paid bit',@ID=1,@ActionID=1258,@Consequence_Paid=NULL,@Date='2017-10-31 19:05:36',@Name=N'Dom C123 ',@Notes=N'Always Wear your licensesasasa',@Reward_Paid=NULL
ExecuteSQLCommand here:
Sub ExecuteSQLCommand(ByVal commandText As String, ByVal params As SqlParameter())
Dim con As New SqlConnection(GetConnectionString())
Try
con.Open()
Dim com As New SqlCommand(commandText, con)
If Not params Is Nothing Then
If params.Count > 0 Then
com.Parameters.AddRange(params)
End If
End If
com.ExecuteNonQuery()
Finally
If con.State = ConnectionState.Open Then
con.Close()
End If
End Try
End Sub
所以,每次我将False发送给布尔参数(aConsequence_Paid,aReward_Paid),我在数据库中得到Null值,怎么样?
谢谢, 德扬
答案 0 :(得分:2)
Nothing
。通过指定Nothing
,未提供的任何参数都将默认为其各自的默认值,因此aConsequence_Paid
将为false。Iif
比较将是一个虚假的比较,以便false = Nothing
评估为真。我建议使用Nullable类型。
Public Function Actions_Update_ByID(Optional aConsequence_Paid = As Boolean? = Nothing)
' ...
ps(2).Value = IIf(aConsequence_Paid.HasValue, aConsequence_Paid.Value, DBNull.Value)
' ...
End Function