I have this procedure in SQL Server and I tried it in SQL Server Management Studio, it works good with my database but in c# it does not work:
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
This is my code in 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;
}
}
}
But this code in C# throws an exception
Object reference was not set to an instance of an object
How can I fix it ?
Thanks
When I debug it, all is fine till this line:
return ((int)(cmd.ExecuteScalar()) == 1) ? true : false;
or I tried this line of code instead of the above one:
object result = (int)(cmd.ExecuteScalar());
The result variable is set to no value because exception occurs just when executing cmd.ExecuteScalar()
Edited:
I figure out that the result value is calculated correctly but not returned into an object as you see here:
Here after executing cmd.ExecuteScalar()
in cmd.parameters
we see four variables (correct) now if we expand count
(the result and returned value form proc) as you see below its value is 1
(then result is correct) but the object that cmd.ExecuteScalar()
returns is null.