我正在尝试更新我的数据库中的值(同时返回状态消息)并且收到以下 InvalidCastError - Object cannot be cast from DBNull to other types。但是,信息会在数据库中更新。它似乎只是不想返回“真”或等效的成功。代码如下图:
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