EF6存储过程必须声明标量变量

时间:2015-09-17 11:39:11

标签: c# asp.net-mvc entity-framework stored-procedures

我正在尝试使用C#EF6调用存储过程来恢复数据。我试图在SQL管理工作室中运行存储过程,它似乎工作正常,但是当我尝试在我的应用程序中运行它时,我收到错误"Must declare the scalar variable "@devID"

以下是我的应用程序中调用存储过程

的方法的一部分
 public IHttpActionResult GetMetrics(int deviceID, string attribute, string startDate)
    {

        if (deviceID == 0)
        {
            return NotFound();
        }

        var metrics = db.Database.SqlQuery<Metrics>("GetMetrics @devID, @MetricType, @startTime", deviceID, attribute, startDate).ToList();

这是我的存储过程:

    ALTER PROCEDURE [dbo].[GetMetrics]
    -- Add the parameters for the stored procedure here
    @devID int,
    @MetricType nvarchar(20),
    @startTime nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * 
    FROM dbMetrics
    WHERE deviceID = @devID and MetricType = @MetricType and timeStamp >= @startTime
    ORDER BY timeStamp 
END

1 个答案:

答案 0 :(得分:5)

根据documentation,如果要使用命名参数,则需要传递SqlParameter这样的对象:

var metrics = db.Database.SqlQuery<Metrics>("GetMetrics @devID, @MetricType, @startTime", 
    new SqlParameter("devID", deviceID),
    new SqlParameter("MetricType", attribute),
    new SqlParameter("startTime", startDate)
).ToList();