简体   繁体   中英

EF6 stored procedure must declare scalar variable

I am trying to call a stored procedure using C# EF6 to bring back data. I have tried to run the stored procedure in SQL management studio and it seems to work fine, however when I try to run it in my application I get an error saying "Must declare the scalar variable "@devID"

Here is part of my method in my application calling the stored procedure

 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();

and here is my stored procedure:

    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

As per the documentation , if you want to use named parameters, you need to pass SqlParameter objects like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM