【问题标题】:How can I call a stored procedure where my code is using Entity Framework [duplicate]如何在我的代码使用实体框架的情况下调用存储过程 [重复]
【发布时间】:2015-11-25 04:53:04
【问题描述】:

我正在尝试调用以下存储过程来显示具有特定产品类型的产品列表。

CREATE PROCEDURE filterListSP
    @productType varchar (25)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        ProductId, Description, Price 
    FROM
        tblProduct 
    WHERE
        ProductType = @productType
END
GO

这是调用 SP 的代码:

dataGridView1.DataSource = naafiDbEntity.Database.SqlQuery<tblProductType>
    ("filterListSP @productType", cboFilter.SelectedValue).ToList();

但是,当我运行此代码时,我收到以下错误:

必须声明标量变量“@productType”

谁能告诉我我错过了什么?

【问题讨论】:

  • 这里也有类似的问题:stackoverflow.com/questions/4873607/…
  • 我(我猜是@MarcoHurtado)花了大约 10 秒的时间在 Google 上搜索到了同样的问题,你怎么没找到?
  • 我很抱歉我是编码新手并尝试在谷歌上搜索答案,但是从另一个问题我现在收到此错误:数据读取器与指定的'NaafiDatabaseModel.tblProductType'不兼容.类型的成员“ProductType”在数据读取器中没有同名的对应列。
  • 好吧,我建议您的模型类与存储过程的返回类型不匹配。

标签: c# entity-framework stored-procedures


【解决方案1】:

像这样在您的 dbcontext 中定义一个函数。 然后通过这种方式拨打电话 例如:dbcontext.SP_Insert(data,value);

            public virtual int SP_Insert(string productType, ObjectParameter retValue)
            {
                var xmlDataParameter = xmlData != null ?
                    new ObjectParameter("productType", xmlData) :
                    new ObjectParameter("productType", typeof(string));

                return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("SP_Insert", xmlDataParameter, retValue);
            }

这里的存储过程是SP_Insert

【讨论】:

    【解决方案2】:

    感谢所有我最终设法解决了。

    这是我将代码修改为的内容

        string result = cboFilter.SelectedValue.ToString();
        dataGridView1.DataSource = naafiDbEntity.filterListSP(result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多