无法拨打"选择"首先使用EF6代码从数据库中存储过程

时间:2015-08-27 11:52:58

标签: c# sql-server entity-framework ef-code-first

此代码失败并显示错误:"必须声明标量值@ prodID"。有什么建议吗?

using (var ctx = new StewieDataModel())
    {
        string productID = "81";

        var techData = ctx.Database.SqlQuery<TechData>("dbo.usp_DS_GetTechData @prodID", productID).ToList();
     }

这是模特:

namespace DatasheetData
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class StewieDataModel : DbContext
{
    public StewieDataModel()
        : base("name=StewieConnectionString")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
}

}

这是我要填充的课程:

namespace DatasheetData
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

[Table("usp_DS_GetTechData")]
public partial class TechData
    {

        public string TestCategory { get; set; }

        public string TestName { get; set; }

        public string TestResultLabel { get; set; }

        public string TestResult { get; set; }

        public string TestMethod { get; set; }
    }
}

以下是我在SSMS中成功调用它的方法:

DECLARE @return_value int

EXEC    @return_value = [dbo].[usp_DS_GetTechData]
        @prodID = "81"

SELECT  'Return Value' = @return_value

GO

SSMS结果是四列VarChar数据: enter image description here

2 个答案:

答案 0 :(得分:2)

您需要将参数作为SqlParameter对象传递。这样的事情应该有效:

var techData = ctx.Database.SqlQuery<TechData>(
        "dbo.usp_DS_GetTechData @prodID", 
        new SqlParameter("prodID", productID)
    ).ToList();

答案 1 :(得分:0)

DavidG正确答案的简写替代方法是:

var techData = ctx.Database.SqlQuery<TechData>(
              "dbo.usp_DS_GetTechData @prodID = {0}", productID).ToList();

explained here