简体   繁体   中英

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):

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
  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#?

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 .

It is similar to how ASP.NET MVC allows any number of parameters to be sent to an Action. Your stored procedure will retrieve the parameters it needs from the dictionary by their key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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