在B#和MS SQL Server中将布尔类型传递给位参数类型

我有一个C#方法接受clientId(int)和hasPaid(boolean),表示客户端是否已付款。 MS SQL Server存储过程需要@HasPaid参数的BIT值(1或0),但该方法需要hasPaid的boolean类型(true / false)。 ADO.NET代码是否会将boolean转换为SQL Server的bit类型,还是需要将hasPaid的值转换为1 or 0

 public void UpdateClient(int clientId, bool hasPaid) { using (SqlConnection conn = new SqlConnection(this.myConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand("uspUpdatePaymentStatus", conn)) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@ClientID", clientId); sqlCommand.Parameters.AddWithValue("@HasPaid", hasPaid); sqlCommand.Connection.Open(); var rowsAffected = sqlCommand.ExecuteNonQuery(); } } } 

使用SQL参数时,我发现AddWithValue的类型自动检测function太不可靠了。 我发现最好只调用Add a显式设置类型, Add也返回它从函数调用创建的新参数,这样你就可以在之后调用.Value

 public void UpdateClient(int clientId, bool hasPaid) { using (SqlConnection conn = new SqlConnection(this.myConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand("uspUpdatePaymentStatus", conn)) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add("@ClientID", SqlDbType.Int).Value = clientId; sqlCommand.Parameters.Add("@HasPaid", SqlDbType.Bit).Value = hasPaid; sqlCommand.Connection.Open(); var rowsAffected = sqlCommand.ExecuteNonQuery(); } } } 

使用正确的类型在使用存储过程时非常重要,并且它期望特定类型,我只是养成了这样做的习惯。