为什么 SQL 语句在对数据库进行时有效,但不能通过 WCF 进行?

Why would a SQL statement work when made to the DB, but not through a WCF?

我还是 .NET 的新手,我不明白为什么 sql 从应用程序到数据库运行良好的语句,现在在我尝试将其卸载到数据库时却不起作用服务。我有一个 Winform,它有一个日期、承运人和上传者复选框,具体取决于所检查的内容,sql 语句应该像应用程序与数据库对话时一样遵守它。我是否必须为每个可能的选项编写一个 OperationContract? (即单独日期、日期和承运人、日期和上传者等....)谢谢!

public DataSet GetStatTableYear(StatDetails statInfo)
    {
        SqlConnection con = new SqlConnection("Data Source=localhost\sqlexpress;Initial Catalog=vurdevice;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand(@"SELECT CONVERT(VARCHAR(4), CreateDate, 112) AS cPeriod, COUNT(DISTINCT IMEINo) AS TotalIMEINo, COUNT(*) AS TotalImageCnt, SUM(FileSize) AS TotalFileSize
                FROM VR_Image
                WHERE (@Uploader IS NULL OR Uploader = @Uploader) 
                AND (@CarrierID IS NULL OR CarrierID = @CarrierID) 
                AND DeleteDate IS NULL
                GROUP BY CONVERT(VARCHAR(4), CreateDate, 112)
                ORDER BY cPeriod", con);
        cmd.Parameters.AddWithValue("@CarrierID", statInfo.CarrierID);
        cmd.Parameters.AddWithValue("@Uploader", statInfo.Uploader);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        cmd.ExecuteNonQuery();
        con.Close();
        return ds;
    }

在您的连接字符串中您使用的是集成安全性,这意味着 Windows 身份验证用于建立连接。

您的 Windows Forms 应用程序 运行 在您的 Windows 帐户安全环境下,它可以连接。

除非您在 IIS 和 web.config 中启用它,否则 WCF 应用程序很可能不使用 Windows 身份验证,在这种情况下,我相信 IIS 应用程序池身份/帐户无法访问数据库建立连接。

这是我现阶段的最佳猜测,因为您还没有解释收到的失败的详细信息。

我找到了一个完美的解决方案。由于服务一直忽略 sql 语句......

WHERE (Uploader IS NULL OR Uploader = @Uploader)
AND (CarrierID IS NULL OR CarrierID = @CarrierID)

我在没有可用的时候给它分配了 DBNull,现在它工作正常。

新代码

public DataSet GetStatTableYear(StatDetails statInfo)
    {
        using (SqlConnection con = new SqlConnection("Data Source=localhost\sqlexpress;Initial Catalog=vurdevice;Integrated Security=True"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(@"SELECT CONVERT(VARCHAR(4), CreateDate, 112) AS cPeriod, COUNT(DISTINCT IMEINo) AS TotalIMEINo, COUNT(*) AS TotalImageCnt, SUM(FileSize) AS TotalFileSize
                    FROM VR_Image
                    WHERE (Uploader IS NULL OR Uploader = @Uploader) 
                    AND (CarrierID IS NULL OR CarrierID = @CarrierID) 
                    AND DeleteDate IS NULL
                    GROUP BY CONVERT(VARCHAR(4), CreateDate, 112)
                    ORDER BY cPeriod", con);
            cmd.Parameters.AddWithValue("@CarrierID", statInfo.CarrierID == null ? DBNull.Value.ToString() : statInfo.CarrierID);
            cmd.Parameters.AddWithValue("@Uploader", statInfo.Uploader == null ? DBNull.Value.ToString() : statInfo.Uploader);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            con.Close();
            return ds;
        }
    }