另一個SqlParameterCollection 中已包含 SqlParameter[解決方案]


本着代碼重用,減少變量的創建,希望參數能夠重復使用

            

//查詢該目錄下的郵件總數
            string strSum = "select count(F_ID) from dbo.T_TLMail_receiver where F_Receiver=@F_Receiver and F_DirID=@F_DirID";
            //查詢該目錄下的未讀郵件數
            string strUnRead = "select count(F_ID) from dbo.T_TLMail_receiver where F_Receiver=@F_Receiver and F_State=0 and F_DirID=@F_DirID";
            SqlParameter[] Params ={ 
                                    new SqlParameter("@F_Receiver",SqlDbType.Int),
                                    new SqlParameter("@F_DirID",SqlDbType.Int)};

            int UnRead, Total;
            DataRow row = null;
            foreach (KeyValuePair<int, string> item in dirs)
            {
                Params[0].Value = userID;
                Params[1].Value = item.Key;
                Total = DataHelper.SqlHelper.GetCount(strSum, Params, connection);
                if (Total > 0)
                {
                    Params[0].Value = userID;
                    Params[1].Value = item.Key;
                    UnRead = DataHelper.SqlHelper.GetCount(strUnRead, Params, connection);
                }
                row = nTable.NewRow();
                row["F_ID"] = item.Key;
                row["F_Directory"] = item.Value;
                row["F_UnReadCount"] = UnRead;
                row["F_TotalCount"] = Total;
                nTable.Rows.Add(row);
            }

 

錯誤如下:另一個 SqlParameterCollection 中已包含 SqlParameter。
錯誤詳細信息:System.ArgumentException: 另一個 SqlParameterCollection 中已包含 SqlParameter。
具體原因:聲明的SqlParameter數組,而在循環的內部,每一次執行ExecuteNonQuery都由該方法內部的IDbCommand.Parameters.Add(IDbDataParameter)將SqlParameter數組添加到IDbCommand的IDataParameterCollection中。而framework機制限制兩個IDataParameterCollection指向同一個對象。雖然ExecuteNonQuery方法內部聲明了一個IDbCommand的臨時對象,理論上講,這個包含了IDataParameterCollection的IDbCommand對象會在ExecuteNonQuery方法結束時從內存中釋放。但是實際上可能是由於垃圾回收機制並沒有將IDbCommand臨時對象即時的回收,而且改對象綁定的Parameter集合也存在,就像一個DropDownList添加Item一樣。這樣在下一個循環執行的時候,會導致兩個IDataParameterCollection指向同一個對象,此時出現問題。
解決方案一:在每一次循環時,重新生成對象,但這樣會產生大量的垃圾變量,不可取。
解決方案二:將使用完之后的Command命令的Parameters集合清空。
                

PrepareCommand(cmd, con, cmdText, cmdParms);
count= Bmc.CLUtility.getConvertIntValue(cmd.ExecuteScalar());
cmd.Parameters.Clear();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM