When debugging the the following method in a unit test I get the following error
Object reference not set to an instance of an object
when hitting the following line
result = (int)validateDatabase.ExecuteScalar();
The method is
public static Boolean Validate(string argument1, string argument2)
{
int result = -1;
using (var connection = new SqlConnection("connection string"))
{
SqlCommand validateDatabase = new SqlCommand("PROCEDURE NAME", connection);
validateDatabase.CommandType = System.Data.CommandType.StoredProcedure;
validateDatabase.Parameters.Add("@PARAMETER1", System.Data.SqlDbType.NVarChar).Value = argument1;
validateDatabase.Parameters.Add("@PARAMETER2", System.Data.SqlDbType.NVarChar).Value = argument2;
try
{
connection.Open();
result = (int)validateDatabase.ExecuteScalar();
}
catch (SqlException exception) { Trace.WriteLine("exception.Message); }
finally { connection.Close(); }
}
return (int)result == 0 ? true : false;
}
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
ExecuteScalar method is used to execute SQL Commands or storeprocedure, after executing return a single value from the database. It also returns the first column of the first row in the result set from a database.
ExecuteScalar: Use this operation to execute any arbitrary SQL statements in SQL Server to return a single value. This operation returns the value only in the first column of the first row in the result set returned by the SQL statement.
ExecuteScalar Method. Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.
ExecuteScalar
return null if the result set is null according to MSDN. This means that your cast is invalid
See here for the documentation SqlCommand.ExecuteScalar
If you want that cast to work change it to a nullable int
result = (int?)validateDatabase.ExecuteScalar();
I just experienced a similar problem. What I did was to select an int column from a specific record in a table, but it happened the value of that column is 0. Doing the following caused the exception “Object reference not set to an instance of an object”:
int i = (int)cmd.ExecuteScalar();
My solution was to change the above code to:
int i = 0;
object a = cmd.ExecuteScalar();
if (a != null)
i = (int)a;
This avoided the exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With