错误:SqlParameter已包含在另一个SqlParameterCollection中。

错误:SqlParameter已包含在另一个SqlParameterCollection中。

问题描述:

foreach (var item in BranchContactList)
                    {
                        var varInsertBranchContactResult = db.Database.ExecuteSqlCommand("TempspInsertBranchContact @BranchID,@FirstName,@LastName,@Designation,@Department,@PhoneNo1,@PhoneNo2,@MobileNo1,@MobileNo1,@EmailAddress1,@EmailAddress2,@CreatedBy,@CreatedUser,@BranchContactIDOut OUT",
                        new SqlParameter("BranchID", BranchID),
                        new SqlParameter("FirstName", item.FirstName.ToString()),
                        new SqlParameter("LastName", item.LastName.ToString()),
                        new SqlParameter("Designation", item.Designation.ToString()),
                        new SqlParameter("Department", item.Department.ToString()),
                        new SqlParameter("PhoneNo1", item.PhoneNo1.ToString()),
                        new SqlParameter("PhoneNo2", item.PhoneNo2.ToString()),
                        new SqlParameter("MobileNo1", item.MobileNo1.ToString()),
                        new SqlParameter("MobileNo2", item.MobileNo2.ToString()),
                        new SqlParameter("EmailAddress1", item.EmailAddress1.ToString()),
                        new SqlParameter("EmailAddress2", item.EmailAddress2.ToString()),
                        new SqlParameter("CreatedBy", UserID),
                        new SqlParameter("CreatedUser", User), outParamBranchContactID).ToString().ToList();
                        var BranchContactID = (int)outParamBranchContactID.Value;

                      

                    }







如何在这种特殊情况下解决这个问题。



我知道cmd.Parameters.Clear()是一个选项,但我不能在这种情况下使用它。



注意:foreach运行3次。一旦成功。第二次它会抛出一个错误:




How to solve this problem in this particular scenario.

I know cmd.Parameters.Clear() is an option but i cant use it in this scenario.

Note : foreach runs for 3 times. Once successfully. For 2nd time it throws an error :

Error: The SqlParameter is already contained by another SqlParameterCollection






.
.

很可能是你的OUT参数 outParamBranchContactID 。您没有为此执行定义新参数。相反,您使用的预定义参数可能已经与另一个命令相关联。



尝试创建一个新参数并在调用中使用它。
Most likely it's your OUT parameter outParamBranchContactID. You don't define a new parameter for this execution. Instead you use a predefined parameter which may already have been associated with another command.

Try creating a new parameter and use it in the call.