gpt4 book ai didi

c# - ExecuteScalar 调用抛出异常 "Object reference not set to an instance of an object"

转载 作者:可可西里 更新时间:2023-11-01 08:39:39 26 4
gpt4 key购买 nike

在单元测试中调试以下方法时出现以下错误

Object reference not set to an instance of an object

点击以下行时

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;
}

最佳答案

ExecuteScalar 根据 MSDN,如果结果集为 null,则返回 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com