【问题标题】:Unable to call "select" stored procedure using EF6 code first from database无法首先从数据库中使用 EF6 代码调用“选择”存储过程
【发布时间】:2015-08-27 11:52:57
【问题描述】:

此代码因错误而失败:“必须声明标量值@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 数据:

【问题讨论】:

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


    【解决方案1】:

    您需要将参数作为SqlParameter 对象传递。像这样的东西应该可以工作:

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

    【讨论】:

    • 这解决了最初的问题,但是当预期有几个值时,我现在返回零值。不知道如何解决这个问题。谢谢。
    • 运行 SQL Profiler 并准确查看对数据库调用的内容。
    • 我现在得到了结果。谢谢!
    【解决方案2】:

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

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

    作为explained here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多