1

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

3
  • send in an array [] of SqlParameters........ Commented Aug 13, 2015 at 12:54
  • Read about method overloading. of course it is not an answer to your question but method caller feels like calling same method Commented Aug 13, 2015 at 12:55
  • You could just use Dapper. Commented Aug 13, 2015 at 13:09

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.