0

I am calling my stored procedure through the following code:

var DepartmentList = db.Database.SqlQuery<Department>("DpDemoProcedure @iHandle",
       new SqlParameter("@iHandle", "GeDepartment"));

However, I am getting this exception:

The SqlParameter is already contained by another SqlParameterCollection.

This is my stored procedure:

CREATE PROCEDURE DpDemoProcedure
    @iHandle VARCHAR(50) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    IF @iHandle = 'GeDepartment'
    BEGIN
        SELECT * 
        FROM Departments 
        ORDER BY DepartmentName 
    END     
END
GO

I am getting confused where exactly my code working wrong. I am new to Entity Framework.

This my action method where I am returning value

public ActionResult Demo()
{
    var DepartmentList = db.Database.SqlQuery<Department>("DpDemoProcedure @iHandle",
           new SqlParameter("@iHandle", "GeDepartment"));

    return View(DepartmentList);
}

I am using this list for display purpose

@model IEnumerable<MediorbitMain.Department>
@{
    ViewBag.Title = "Demo";
    Layout = "~/Views/shared/_Layout.cshtml";
}

<h2>Demo</h2>

<table>
    <tr>
        <th>DepartmentId</th>
        <th>DepartmentName</th>
    </tr>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.DeptId</td>
                <td>@item.DepartmentName</td>
            </tr>
        }
    </tbody>
</table>
3
  • How are you using the DepartmentList variable in your code? Can you show that? Please edit the question with this detail. Commented Oct 25, 2017 at 14:27
  • My guess is that you are enumerating the DepartmentList multiple times in the view. Can you add a .ToList() and see if that fixes it? e.g. db.Database.SqlQuery<Department>(...).ToList(); Commented Oct 25, 2017 at 15:04
  • this may help : stackoverflow.com/a/46711751/1236044 you may try removing the @ in new SqlParameter("iHandle", "GeDepartment"), but not in the call Commented Oct 25, 2017 at 15:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.