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

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

我正在尝试使用 C# EF6 调用存储过程来取回数据。我曾尝试在 SQL Management Studio 中运行存储过程,它似乎工作正常,但是当我尝试在我的应用程序中运行它时,出现错误提示 "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

最佳答案

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

关于c# - EF6 存储过程必须声明标量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32629440/

相关文章:

asp.net-mvc - 不同 Action 的相同 Action 过滤器

wcf - 如何让 Entity Framework 和 WCF 与事务一起工作?好吧……有什么 secret ?

c# - 为什么连接字符串不适用于 EF 迁移?

c# - 接收 : Create a subsequent observable from an observable with a different type (Chaining observers)

c# - 如何将 task.Wait(CancellationToken) 转换为 await 语句?

c# - System.Uri 类截断尾随 '.' 个字符

c# - WMPLib 经常停止播放

asp.net-mvc - Kendo Treeview 扩展器不来了

asp.net-mvc - Url.Action 产生查询字符串,有什么方法可以产生完整的 url?

c# - Entity Framework 6 + Oracle如何查询两个结构相同的表