I have six lines of parameters like this:
cmd.Parameters.AddWithValue("@variable1", myvalue1);
cmd.Parameters.AddWithValue("@variable2", myvalue2);
cmd.Parameters.AddWithValue("@variable3", myvalue3);
and so on.
Is there any way to compress this a bit without directly inserting in the cmd.CommandText?
Edit: I guess I could have used a good old fashioned array. I've decided to stick with this though.
I took the question literally: "...in one statement" :)
Steve code is nice but it can be simplified a bit more using the most canonical SqlParameter constructor and implicit arrays declaration:
cmd.Parameters.AddRange(new []
{
new SqlParameter("@variable1", myValue1),
new SqlParameter("@variable2", myValue2),
new SqlParameter("@variable3", myValue3),
});
I think this will read very nicely as a one liner like this:
Usage:
// One liner to create and set SqlCommand parameters
cmd.SetParameters(Parameter("@variable1", myvalue1), Parameter("@variable2", myvalue2), Parameter("@variable3", myvalue3));
To support the one liner you need to create a function to wrap the Sql Parameter as a semantic bundle (Tuple like) as follows:
public SqlParameter Parameter(string name, object value)
{
return new SqlParameter(name, value);
}
Create a static class with an extension method to give us the syntactic sugar we are looking for. Notice the use of the params keyword which allows the multiple parameters in the above call to SetParameters.
public static class SqlDataUtils
{
public static void SetParameters(this SqlCommand command, params SqlParameter[] parameters)
{
command.Parameters.AddRange(parameters);
}
}
This answer is inspired by the accepted answer to Key value pairs in C# Params by Bryan Watts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With