简体   繁体   English

C#ASP.NET:创建通用方法以使用任意数量的参数调用存储过程

[英]C# ASP.NET: create general method to call Stored Procedure with any number of parameters

In the project I'm working to in this period I have to work a lot with stored procedures in SQL Server, actually I use this method (using Dapper): 在这个时期我要处理的项目中,我必须在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;
 }

This method has the following two problems: 此方法存在以下两个问题:

  1. Can return only object of foo_type type 只能返回foo_type类型的对象
  2. Accept only two parameters 仅接受两个参数

I'd like to make this method general, so 我想将此方法通用化,所以

  1. I need to pass all the params of the stored procedure 我需要传递存储过程的所有参数
  2. I'd like to tell the function the type of the objects that will be returned from the stored procedure 我想告诉函数将从存储过程中返回的对象的类型

The function declaration will be something like: 函数声明将类似于:

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

Is there a way to do something like this in C#? 有没有办法在C#中做这样的事情?

Try this: 尝试这个:

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);
}

Try passing a Dictionary<string,object> as a parameter and return object . 尝试将Dictionary<string,object>作为参数传递并返回object

It is similar to how ASP.NET MVC allows any number of parameters to be sent to an Action. 这类似于ASP.NET MVC允许将任意数量的参数发送到操作的方式。 Your stored procedure will retrieve the parameters it needs from the dictionary by their key. 您的存储过程将通过其键从字典中检索所需的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM