How to create array DbParameter[]

Tys picture Tys · Aug 17, 2011 · Viewed 17.6k times · Source

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.

Answer

Juan Ayala picture Juan Ayala · Aug 17, 2011
  • 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);