我試圖更新數據庫中的值(同時返回狀態信息)並獲取以下InvalidCastError - 對象無法從DBNull轉換爲其他類型。但是,信息在數據庫中更新。它似乎不想回到'真實'或成功的等值。如下圖所示代碼:即使執行成功,C#對象也不能從DBNull錯誤轉換
C#:
public bool Update(Customer pCustomer)
{
using (SqlConnection sqlConnect = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand sqlComm = new SqlCommand("Update_Customer", sqlConnect))
{
sqlComm.CommandType = CommandType.StoredProcedure;
//Other items to update (Not causing issues)
sqlComm.Parameters.Add("@Message", SqlDbType.Bit).Direction = ParameterDirection.Output;
sqlComm.Connection = sqlConnect;
try
{
sqlComm.Connection.Open();
sqlComm.ExecuteNonQuery();
return Convert.ToBoolean(sqlComm.Parameters["@Message"].Value);
}
catch(Exception)
{
throw;
}
finally
{
sqlComm.Connection.Close();
}
}
}
}
SQL:
//Unrelevent code removed
AS
BEGIN
BEGIN TRY
BEGIN TRAN
BEGIN
UPDATE Customer
SET
Password = @Password,
RecordTimeStamp = @NewRecordTimeStamp
WHERE CustomerID = @CustomerID AND RecordTimeStamp = @OldRecordTimeStamp
END
IF @@ROWCOUNT <> 1
BEGIN
Set @Message = 1
END
IF @@ERROR <> 0
ROLLBACK TRAN
ELSE
COMMIT TRAN
END TRY
BEGIN CATCH
DECLARE @Err nvarchar(500)
SET @Err = ERROR_MESSAGE()
RAISERROR(@Err, 16, 1)
END CATCH
END
GO
你檢查,看看是否有任何您發送或返回是'null'? – Brian 2013-02-27 22:32:10
一切都有一個值,它在數據庫中正確更新。只是似乎沒有註冊成功更新。 – ZeeeeeV 2013-02-27 22:32:54
好吧,數據庫中的所有內容都更新了,但是'@ Message'裏面有「True」還是「False」? – 2013-02-27 22:34:00