【问题标题】:Use EntityFramework Core to call a MSSQL StoredProcedure and show the data returned --使用 Entity Framework Core 调用一个 MYSQL 存储过程并显示返回的数据——
【发布时间】:2018-08-30 14:46:59
【问题描述】:

嗯,这个问题是不言自明的。所以我不会不必要地扩展它。 这是我的 SP--

    CREATE procedure [dbo].[sp_TotalSalesByCustomerID]
    @customer_id nvarchar(50),
    @varSale decimal OUTPUT  
    as

    begin

    begin try

    if exists (
            Select * from tempdb..sysobjects Where id = 
       object_id('tempdb.dbo.#temp')
          )
        DROP TABLE #temp

    else

        select * into #temp from Orders where customer_id=@customer_id

        select @varSale=SUM(total_price) from #temp

    end try

    begin catch
           select error_message(),
           error_severity(),
           error_number(),
           error_state()    
    end catch

    end

如您所见,SP 基本上只返回一个计算值。它没有映射到我的应用程序中的任何实体对象/类。 我写的后端 web api 端的 C# 代码 --

[Route("TotalSalesByCustomerID")]
    [HttpPost]
    public JsonResult TotalSalesByCustomerID([FromBody]string customer_id)
    {
        try
        {
            //var salesT = (_appDbContext.Totals.FromSql("call sp_TotalSalesByCustomerID(@customer_id)", customer_id));
            var salesT= _appDbContext.Database.ExecuteSqlCommand("sp_TotalSalesByCustomerID @p0", parameters: new[] { customer_id });
            return Json(salesT);
        }
        catch(Exception exp)
        {
            return Json(exp.GetBaseException());
        }
    }

我不知道它返回的是什么 codswallop 垃圾。可能是因为它没有映射到实体类对象。我明白那个。可能某些 C# 代码也是错误的。我也不需要单独的课程。它只是一个值!如果我添加一个类,我可能也需要进行迁移,这在我的场景中是不必要的。 仅供参考,这也是我的迁移构建器类,我在“Up and 'Down”中添加了我的 sql 代码 --

protected override void Up(MigrationBuilder migrationBuilder)
    {
        var sp = @"CREATE procedure [dbo].[sp_TotalSalesByCustomerID]
                    @customer_id nvarchar(50),
                    @varSale decimal OUTPUT  
                    as

                    begin

                    begin try

                    if exists (
                                Select * from tempdb..sysobjects Where id = object_id('tempdb.dbo.#temp')
                              )
                            DROP TABLE #temp

                    else

                            select * into #temp from Orders where customer_id=@customer_id

                            select @varSale=SUM(total_price) from #temp

                    end try

                    begin catch
                        select error_message(),
                               error_severity(),
                               error_number(),
                               error_state()    
                    end catch

                    end";

        migrationBuilder.Sql(sp);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        var sp = @"CREATE procedure [dbo].[sp_TotalSalesByCustomerID]
                    @customer_id nvarchar(50),
                    @varSale decimal OUTPUT  
                    as

                    begin

                    begin try

                    if exists (
                                Select * from tempdb..sysobjects Where id = object_id('tempdb.dbo.#temp')
                              )
                            DROP TABLE #temp

                    else

                            select * into #temp from Orders where customer_id=@customer_id

                            select @varSale=SUM(total_price) from #temp

                    end try

                    begin catch
                        select error_message(),
                               error_severity(),
                               error_number(),
                               error_state()    
                    end catch

                    end";

        migrationBuilder.Sql(sp);
    }

我不知道该怎么办。当然,我在这里错过了一些不错的技巧或一些技巧。它是什么?我可以制作某种虚拟/抽象实体,我可以在 EF Core 中使用它来获取我的数据,而不是创建表、向我的数据库添加迁移等吗?还有哪些选择? 我期待在这方面提供一些好的帮助。 谢谢大家,

【问题讨论】:

  • 您永远不应该通过存储过程返回值返回数据。这是一种旧机制,仅用于指示成功或失败。使用输出参数或结果集。或者使用函数而不是存储过程。
  • ok @DavidBrowne-Microsoft 让我更新 SP 的代码清单。更改。接下来,对于这个问题,我可能已经这样做了?请建议,
  • @DavidBrowne-Microsoft 我更新了 dmy SP,现在正在使用输出参数。但就像其他评论者指出的那样 - 使用 ExecuteSqlCommand 我只得到行数而不是我的输出参数值。我该怎么办?我需要 SP 返回的值。
  • ExecuteSqlCommand 检查outptutParam.Value的值
  • @DavidBrowne-Microsoft okk 让我检查一次;

标签: sql-server entity-framework entity-framework-core asp.net-core-webapi entity-framework-migrations


【解决方案1】:

您必须使用返回值的输出参数 instdead,如下面的代码。

var outputParam = new SqlParameter("outputParam", SqlDbType.Int) { Direction = ParameterDirection.Output };
await _databaseContext.Database.ExecuteSqlCommand($"EXEC {storedProcedureName} @param1, @outputParam output", new SqlParameter("param1"), outputParam);

要得到你需要在上面两行之后调用outputParam.Value的值。

ExecuteSqlCommand() 的返回值是一个整数,表示受查询影响的记录数。

【讨论】:

  • 我明白了,感谢@vivek-nuna 的回复;让我更新代码块并查看响应;
  • 我已经更新了 SP。它现在将 varSale 作为 OUTPUT 返回。但是我如何接收这个值?因为 ExecuteSqlCommand 没有给我。它没有。像 4、7 这样的行。不是输出的那个值。怎么可能??
  • 您需要将此输出参数传递给 SP,就像我在示例代码中所做的那样。
  • 是的,它现在工作正常; outputParam.Value 给了我 SP 返回的值。
猜你喜欢
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 2021-11-08
  • 1970-01-01
  • 2020-05-21
相关资源
最近更新 更多