在单元测试中调试以下方法时,出现以下错误
当点击以下行时
result = (int)validateDatabase.ExecuteScalar();
方法是
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;
}
最佳答案
根据MSDN,如果结果集为null,则ExecuteScalar
返回null。这意味着您的演员表无效
请参阅此处以获得SqlCommand.ExecuteScalar文档
如果您要强制转换,请将其更改为可为空的int
result = (int?)validateDatabase.ExecuteScalar();
关于c# - ExecuteScalar调用引发异常 “Object reference not set to an instance of an object”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20117825/