To take my previous post to the next level, I decided to try a different approach to adding parameters to an IDbCommand by using anonymous types. This is inspired by the way you set up routes in ASP.NET MVC, and example of which you can see here on ScottGu's blog. The idea is that you simply pass in an anonymous type, whose properties match the parameter names you want to define.

First, here's the extension method:

internal static void AddInputParameters<T>(this IDbCommand cmd,
    T parameters) where T : class
{
    foreach (var prop in parameters.GetType().GetProperties())
    {
        object val = prop.GetValue(parameters, null);
        var p = cmd.CreateParameter();
        p.ParameterName = prop.Name;
        p.Value = val ?? DBNull.Value;
        cmd.Parameters.Add(p);
    }
}

So I'm iterating through the properties of "parameters", and for each one I'm adding an input parameter based on its value. I'm supporting null by simply adding a parameter with DBNull.Value.

Note that this has a slightly different behaviour with strings than my previous attempt, in that it will not treat an empty string as DBNull, but I think this is probably preferable.

Here's how you'd use it:

cmd.AddInputParameters(new
    {
        Date = eventDate,
        Operator = oper,
        Weight = weight
    });

Pretty succinct! Of course it's no more compile-checked than literal strings (except for the fact that it only allows valid identifiers as parameter names), but it's much more readable than a small chunk of code for each parameter.