The SqlParameter is already contained by another SqlParameterCollection

public List<dbEntity.models.user> searchUser(string strUserCode,string strUserName,string strUserAccount) {
            using (dbEntity.dbEntity db = new dbEntity.dbEntity()) {
                object[] objParams = new object[3];
                objParams[0] = new SqlParameter() { ParameterName = "@usercode", Value = strUserCode ?? DBNull.Value.ToString() };
                objParams[1] = new SqlParameter() { ParameterName = "@username", Value = strUserName ?? DBNull.Value.ToString() };
                objParams[2] = new SqlParameter() { ParameterName = "@useraccount", Value = strUserAccount ?? DBNull.Value.ToString() };

                var vRes = db.Database.SqlQuery<dbEntity.models.user>("exec sp_searchUser @usercode,@username,@useraccount", objParams.Select(x => ((ICloneable)x).Clone()).ToArray());

//vRes其實並沒有真正的取數據


                return vRes.ToList();//ToList才真正的取到數據
            }
                
           
        }

1.第一次沒有使用using,所以理解的是ef中的sqlcommand  parameter資源沒有釋放,後來用using還是報相同的錯誤,

只好用((ICloneable)x).Clone()).ToArray() 將parameter暫時copy出來處理。

 

沒有搞明白具體的原因是什麼,先記錄一下。

 

參考:

https://stackoverflow.com/questions/30575555/getting-the-sqlparameter-is-already-contained-by-another-sqlparametercollection

https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter.system-icloneable-clone?redirectedfrom=MSDN&view=netframework-4.7.2#System_Data_SqlClient_SqlParameter_System_ICloneable_Clone

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章