【问题标题】:How do I call stored procedures in EF Core 6 using named parameters?如何使用命名参数在 EF Core 6 中调用存储过程?
【发布时间】:2022-06-11 15:56:10
【问题描述】:

许多代码示例使用命名参数或执行存储过程,但不能同时使用两者。当存储过程没有选择预定义的实体类型时,我该怎么做? (这意味着.FromSqlRaw 不在了。)

【问题讨论】:

  • FromSqlRaw 在 EF Core 中,检查你的使用情况
  • @ErikEJ 原来我(错误地)假设我应该能够直接对 DatabaseFacade 使用它。 (我没有预定义的实体,我第一次尝试设置 IntValue 实体类型失败了,但我不知道为什么。)您的评论鼓励我再试一次,这次我明白了。谢谢。
  • @ErikEJ 顺便说一句,我找到了这个链接,我猜它是你的。非常有帮助。 erikej.github.io/efcore/2020/05/26/ef-core-fromsql-scalar.html

标签: entity-framework-core ef-core-6.0


【解决方案1】:

下面的代码允许您调用存储过程并生成命名参数列表,只需来自SqlParameters 列表。

var sqlParams = new SqlParameter[] {
  new SqlParameter("p1", valOfP1),
  new SqlParameter("p2", valOfP2),
  new SqlParameter("pOut", SqlDbType.Int)
  {
    Direction = System.Data.ParameterDirection.Output
  }
};

// OK to use the same names as for the SqlParameter identifiers. Does not interfere.
var sql = "myStoredProc " + String.Join(", ", sqlParams.Select(x =>
  $"@{x.ParameterName} = @{x.ParameterName}" +
  (x.Direction == ParameterDirection.Output ? " OUT" : "")
  ));

myDbContext.Database.ExecuteSqlRaw(sql, sqlParams);

var outputId = (int)(sqlParams.First(p => p.Direction == ParameterDirection.Output).Value);

【讨论】:

  • 感谢您发布此信息。对于我们这些已经放弃希望 EF Core 为 Entity Framework 提供存储过程一流公民支持的人来说,这是一个很好的准系统模式,并且他们不希望不得不通过无数的包装器和库来搜索只是为了得到执行一个简单的过程。
【解决方案2】:

试试下面的示例代码,它可以让您调用 sp 并将结果存储在 数据表。

using (var command = db.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = "sp_name";
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add(new SqlParameter("key", "Value"));

                db.Database.OpenConnection();

                using (var result = command.ExecuteReader())
                {
                    var dataTable = new DataTable();
                    dataTable.Load(result);
                    return dataTable;
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多