在ASP.NET MVC 5中使用Entity Framework调用select存储过程

时间:2017-10-25 14:25:40

标签: asp.net-mvc entity-framework

我通过以下代码调用我的存储过程:

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

但是,我得到了这个例外:

  

另一个SqlParameterCollection已经包含了SqlParameter。

这是我的存储过程:

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

我对我的代码工作错误的地方感到困惑。我是Entity Framework的新手。

这是我的行动方法,我将返回值

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

    return View(DepartmentList);
}

我将此列表用于显示目的

@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>

0 个答案:

没有答案