Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array DbParameter[]

The manual says that the ExecuteScalar method should be used like:

public T ExecuteScalar<T>( 
   string commandText,
   CommandType commandType,
   params DbParameter[] parameters
)

But how do I create that array of parameters? I need to provide my stored procedure 2 parameters.

like image 384
Tys Avatar asked Aug 17 '11 18:08

Tys


2 Answers

  • DbParameter is an abstract class.
  • Since the type T can not be inferred from the usage, you have to specify it.
  • Althought you can just pass a variable number of parameters without creating the array, if you are dynamically creating a variable number of parameters, the array is your friend.

    var parameters = new[]{
                new SqlParameter(){ ParameterName="foo", Value="hello" },
                new SqlParameter(){ ParameterName="bar", Value="World" }
            };
    x.ExecuteScalar<int>(commandText, commandType, parameters);
    
like image 100
Juan Ayala Avatar answered Sep 19 '22 15:09

Juan Ayala


The parameters parameter has the params keyword. This means that you don't have to create the array explicitly but can pass a variable number of arguments to the method:

x.ExecuteScalar(commandText, commandType, parameter1, parameter2);

However, if you want, you can create the array explictly and pass it to the method as follows:

DbParameter[] parameters = new DbParameter[] { parameter1, parameter2 };

x.ExecuteScalar(commandText, commandType, parameters);
like image 37
dtb Avatar answered Sep 23 '22 15:09

dtb