Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 指定的强制转换无效-System.InvalidCastException_C#_Sql Server_Asp.net Mvc 5 - Fatal编程技术网

C# 指定的强制转换无效-System.InvalidCastException

C# 指定的强制转换无效-System.InvalidCastException,c#,sql-server,asp.net-mvc-5,C#,Sql Server,Asp.net Mvc 5,我读过很多类似的问题,尝试过几种不同的方法,但我不明白为什么这样做不起作用。要求和的列为int类型。我试过对uint和int32进行铸造。我欣赏方向。多谢各位 int i = 1; int total=0; while (i < 7) { string conString = @"Data Source=UATDB2\sqleuat;Initial Catalog=CVNee;User ID=appu

我读过很多类似的问题,尝试过几种不同的方法,但我不明白为什么这样做不起作用。要求和的列为int类型。我试过对uint和int32进行铸造。我欣赏方向。多谢各位

        int i = 1;
        int total=0;
        while (i < 7)
        {

            string conString = @"Data Source=UATDB2\sqleuat;Initial Catalog=CVNee;User ID=appuser;Integrated Security=true";

            SqlConnection connection = new SqlConnection(conString);
            connection.Open();
            SqlCommand cmd = connection.CreateCommand();
            cmd.CommandText = "SELECT SUM(AMOUNT) FROM TRANSACTIONS_DETAIL2 WHERE TRANSACTIONS_DETAIL2.TRANS_TYPE =" + i + "AND TRANSACTIONS_DETAIL2.HOH_UPI = '185292000'";

           int amt = ((int)cmd.ExecuteScalar());
            //amt = cmd.ExecuteScalar();

            if (i == 1)
            {
                total = total + amt;
            }

            if (i == 2)
            {
                total = total - amt;
            }

            if (i == 3)
            {
                total = total - amt;
            }

            if (i == 4)
            {
                total = total + amt;
            }

            if (i == 5)
            {
                total = total + amt;
            }

            if (i == 6)
            {
                total = total + amt;
            }

            connection.Close();
            ViewBag.TotalBalance = total;

            i++;
        }
inti=1;
int-total=0;
而(i<7)
{
string conString=@“数据源=UATDB2\sqleuat;初始目录=CVNee;用户ID=appuser;集成安全性=true”;
SqlConnection连接=新的SqlConnection(构造);
connection.Open();
SqlCommand cmd=connection.CreateCommand();
cmd.CommandText=“从交易详情2中选择金额,其中交易详情2.TRANS\u TYPE=“+i+”和交易详情2.HOH\u UPI='185292000';
int amt=((int)cmd.ExecuteScalar());
//amt=cmd.ExecuteScalar();
如果(i==1)
{
合计=合计+金额;
}
如果(i==2)
{
总计=总计-金额;
}
如果(i==3)
{
总计=总计-金额;
}
如果(i==4)
{
合计=合计+金额;
}
如果(i==5)
{
合计=合计+金额;
}
如果(i==6)
{
合计=合计+金额;
}
connection.Close();
ViewBag.TotalBalance=总计;
i++;
}
根据您的评论 如果调用
ExecuteScalar
,您可能会得到
null
DBNull
,您应该同时选中这两个选项。您可以首先将其填充到
object
类型的变量中,然后检查
DBNull.Value
null
并对此作出反应:

int amt=0;
object amtUnchecked = cmd.ExecuteScalar();
if(amtUnchecked != DBNull.Value && amtUnchecked!=null)
    amt=(int)amtUnchecked;

或者您更改
SELECT
以返回一个确定的零:
SELECT ISNULL(SUM(AMOUNT),0).
ExecuteScalar
返回
null
时,会发生非法强制转换异常。您可以在转换为
int
之前检查结果是否为
null

 object o = cmd.ExecuteScalar();
 int result = o == null ? 0 : (int)o;
或者您可以使用可为空的int
int?
,如果它有值,也可以检查它

 int? result = (int?)cmd.ExecuteScalar();
 if (!result.HasValue) result = 0;
或者,即使没有找到匹配的行,也可以调整查询以返回
0
。TSQL函数
COALESCE
检查第一个参数是否为
NULL
,如果为否,则返回值,如果为是,则返回第二个参数的值

 string query = "SELECT COALESCE(SUM(AMOUNT),0) FROM TRANSACTIONS_DETAIL2 WHERE TRANSACTIONS_DETAIL2.TRANS_TYPE =" + i + "AND TRANSACTIONS_DETAIL2.HOH_UPI = '185292000'";

如果总和返回null,我想你会得到这样的错误。是的,我也注意到了。我现在使用Convert.ToInt32,得到了一个更详细的异常。处理潜在空值的最佳方法是什么?与SQL相关的问题几乎总是这样:不要使用字符串连接创建查询,而是使用参数化查询,因为它们会阻止SQL注入。当我确保sum查询不返回空值时,代码会起作用。问题在于能够控制将amt转换为int时返回的空值。有什么想法吗?这是错误的,我不确定是隐式调用了
ToString()
,还是
+
运算符重载了
String+int
@derpirscher,是的,你是对的。我将从我的答案中删除这部分…@Shnugo我试着像你回答的那样使用ISNULL:但是我得到一个例外,说“关键字'from'附近的语法不正确”。谢谢你的帮助@vmil,您的语法不正确:
ISNULL()
函数需要第二个参数(在
NULL
的情况下的值)和一个结束参数:
ISNULL(SUM(AMOUNT),0)FROM…
ExecuteScalar
如果结果集绝对为空,将返回
NULL
,或者
DBNull
,如果有行,但没有什么可总结的。在代码中,不处理DBNull的情况。我必须承认,我的答案——反之亦然——没有涵盖
null
:-)所以——你和我一起——给出了正确的答案