我在SQL Server中有此過程,我在SQL Server Management Studio中嘗試過它,它對我的數據庫很好,但在c#中不起作用:對象引用未設置爲C#中的對象SQL Server實例
Create Procedure BorrowIsCorrect
@ProductName nvarchar(100),
@PersonId nvarchar(50),
@HBD bit,
@count int output
as
Begin
select @count = count(*)
from BorrowTable
where Person_Identity = @PersonId
and Product_Name = @ProductName
and H_B_D = @HBD
return @count
end
這是我在C#代碼:
internal bool BorrowIsCorrect(Borrow borrow)//checks if some person has some specific product and has not Delivered it yet
{
using (SqlConnection conn2 = new SqlConnection(_ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn2.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "BorrowIsCorrect";
cmd.Connection = conn2;
SqlParameter Output = new SqlParameter("@count", SqlDbType.Int);
Output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(Output);
cmd.Parameters.Add("@ProductName", SqlDbType.NVarChar).Value = borrow.Product.Productname;
cmd.Parameters.Add("@PersonId", SqlDbType.NVarChar).Value = borrow.Person.Id;
cmd.Parameters.Add("@HBD", SqlDbType.Bit).Value = borrow.Has_been_received;
//int result = (int)(cmd.ExecuteScalar());
return ((int)(cmd.ExecuteScalar()) == 1) ? true : false;
}
}
}
但這個代碼在C#中拋出一個異常
對象引用未設置到一個對象的實例
我該如何解決它?
感謝
當我調試它,一切都很好,直到這條線:
return ((int)(cmd.ExecuteScalar()) == 1) ? true : false;
或我想這行代碼,而不是上述之一:
object result = (int)(cmd.ExecuteScalar());
結果變量設置爲無值,因爲執行時發生異常cmd.ExecuteScalar()
編輯:
我弄清楚,結果每次都正確,但不計算返回到一個對象,你在這裏看到:
在這裏,在cmd.parameters
執行cmd.ExecuteScalar()
後,我們可以看到四個變量(正確)現在如果我們展開count
(結果和返回值的形式proc),如下所示它的值爲1
(則結果是正確的)但cmd.ExecuteScalar()
返回的對象爲空。
檢查你'borrow'變量及其'個人或Product'內部類實例 – Steve 2015-02-05 22:21:27
沒有借用和人員和產品null.i試過這個功能不使用StoredProcedure,它運作良好,但使用程序不工作! – ako 2015-02-05 22:24:15
whay downvote?我知道nullreference的異常,但是這個看起來有點不同,並且在StackOverflow鏈接 – ako 2015-02-05 22:27:20