【问题标题】:C# ASP.NET: create general method to call Stored Procedure with any number of parametersC# ASP.NET:创建通用方法以使用任意数量的参数调用存储过程
【发布时间】:2015-08-13 12:50:47
【问题描述】:

在这段时间我正在做的项目中,我必须在 SQL Server 中使用存储过程进行大量工作,实际上我使用这种方法(使用 Dapper):

public static foo_type call_stored_procedure(string stored_procedure_name, string ConnectionString, type_param_1 param1, type_param_2 param2)
{
    using (var connection = new SqlConnection(ConnectionString))
    {
         connection.Open();
         var server_return = connection.Query<foo_type>(stored_procedure_name,
                        new { param1 = param1, param2 = param2 }, commandType: CommandType.StoredProcedure);

         if (server_return != null)
             return server_return;
     }

     return null;
 }

这种方法存在以下两个问题:

  1. 只能返回foo_type类型的对象
  2. 只接受两个参数

我想让这个方法通用,所以

  1. 我需要传递存储过程的所有参数
  2. 我想告诉函数将从存储过程返回的对象的类型

函数声明将类似于:

public static <T> call_stored_procedure(string stored_procedure_name, string ConnectionString, <T> type, <T> params...)

有没有办法在 C# 中做这样的事情?

【问题讨论】:

  • 发送SqlParameters的数组[].......
  • 了解方法重载。当然这不是您问题的答案,但方法调用者感觉就像调用相同的方法
  • 你可以使用Dapper。

标签: c# asp.net sql-server stored-procedures refactoring


【解决方案1】:

试试这个:

public T CallStoredProcedure<T>(connectionString, procName, params object[] parameters)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        var server_return = connection.Query<T> (procName, parameters, commandType:  CommandType.StoredProcedure);
        if (server_return != default(T))
            return server_return;
        }
        return default(T);
}

【讨论】:

    【解决方案2】:

    尝试将Dictionary&lt;string,object&gt; 作为参数传递并返回object。

    这类似于 ASP.NET MVC 允许将任意数量的参数发送到 Action 的方式。您的存储过程将通过键从字典中检索所需的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 2020-04-08
      • 2017-09-29
      • 1970-01-01
      • 2021-08-26
      • 2013-10-16
      相关资源
      最近更新 更多