【问题标题】:Running Postgres stored procedure with C#使用 C# 运行 Postgres 存储过程
【发布时间】:2021-07-25 23:33:08
【问题描述】:

我创建了一个存储过程stocks.public.daily_actions_full(),它不会接收或返回任何内容,它只是将数据从视图插入到表中。

使用dbcontext scaffold后,除了存储过程之外,所有的表和视图都被添加了。

我看到这是一个已知问题,调用存储过程的选项是使用ExecuteSqlCommand

我尝试了以下代码:

using (var db = new stocksContext())
{
    var rowsAffected = db.Database.ExecuteSqlCommand("CALL stocks.public.daily_actions_full()");
}

但我收到以下错误:

不确定我在这里遗漏了什么,或者是否有另一种调用存储过程的方法。

也许手动将其添加到上下文文件中? (找不到方法)

谢谢!

【问题讨论】:

  • ExecuteSqlCommand 在 3.1 之后从 EF 核心中删除。有ExecuteSqlCommandAsync
  • 我仍然收到上面提到的错误。 'DatabaseFacade' does not contain a definition for 'ExecuteSqlCommandAsync' and no accessible extension method 'ExecuteSqlCommandAsync' accepting a first argument of type 'DatabaseFacade' could be found
  • 文件顶部有using System.Data.Entity;吗?
  • DatabaseFacade 类中没有 ExecuteSqlCommand 方法。有ExecuteSqlRawExecuteSqlInterpolated 方法(以及它们的异步版本)。

标签: c# postgresql stored-procedures entity-framework-core


【解决方案1】:

确保您已安装包 Npgsql.EntityFrameworkCore.PostgreSQL 和 Microsoft.EntityFrameworkCore.SqlServer

没有任何参数的重载ExecuteSqlCommand。所以试试这个

 var rowsAffected = db.Database
.ExecuteSqlCommand("Call stocks.public.daily_actions_full()", null);


更新

您可以尝试使用 ExecuteSqlRaw,但在这种情况下,您将需要更多代码

为返回结果创建模型

public class SpResult
{
 public int RowsAffected {get; set;}
}

然后将此模型添加到 dbcontext 中

  public virtual DbSet<SpResult> SpResults { get; set; }

   //and OnModelCreating

   modelBuilder.Entity<SpResult>(e =>
            {
                e.HasNoKey();
            });

只有在此之后,您才能从 SP 获得结果


public string GetApproverCode(int ReqId)
    {
       var rowsAffectedObj = db.SpResults.ExecuteSqlRaw("Call stocks.public.daily_actions_full()", null)
              .ToList()
             .FirstOrDefault();
   
  var rowsAffected=0; 

 if(rowsAffectedObj !=null) rowsAffected= rowsAffectedObj.RowsAffected;

【讨论】:

  • 我仍然收到上面提到的错误。 'DatabaseFacade' does not contain a definition for 'ExecuteSqlCommand' and no accessible extension method 'ExecuteSqlCommand' accepting a first argument of type 'DatabaseFacade' could be found
  • 您能发布您的启动信息吗?您使用的是哪种 dbcontext?
  • 不是所需的命令类型,而不是“exec”部分
  • 是的,您当然需要它来执行存储过程。执行或执行
  • 抱歉,它是针对 MS Sql Server 的。但是对于 Postgresql 则使用 Call
【解决方案2】:

正如@Alexander Petrov 在这里写的:
使用 ExecuteSqlRaw 来解决它。
感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多