Question

Is there anyway I can make this database code any shorter ? It works fine, but seems very verbose and repetitive. Wrapping some of it in a method would be better I suppose, but is there other improvement that could be made to shorten it ?

using (IDbConnection theConn = GetDatabaseConnection())
using (IDbCommand theCmd = theConn.CreateCommand())
{
    theCmd.CommandText = @"INSERT INTO table(one, two, three,four)
                                   VALUES (@one,@two,@three,@four)";
    var parameterOne = theCmd.CreateParameter();
    parameterOne.ParameterName = "@one";
    parameterOne.Value = "text";
    theCmd.Parameters.Add(parameterOne);

    var parameterTwo = theCmd.CreateParameter();
    parameterTwo.ParameterName = "@two";
    parameterTwo.Value = "text";
    theCmd.Parameters.Add(parameterTwo);

    var parameterThree = theCmd.CreateParameter();
    parameterThree.ParameterName = "@three";
    parameterThree.Value = "text";
    theCmd.Parameters.Add(parameterThree);

    var parameterFour = theCmd.CreateParameter();
    parameterFour.ParameterName = "@four";
    parameterFour.Value = "text";
    theCmd.Parameters.Add(parameterFour);

    theCmd.ExecuteNonQuery();
 }
Was it helpful?

Solution

If you don't want use a full OR/M why dont try Dapper?

OTHER TIPS

If you are looking for a general change, I recommend using the Microsoft Entity Framework (or any other OR/M). This will result in much less code as you do not have to write this kind of low level code again. And it works well with many, many databases. You can change the underlying database with relatively small changes.

If you are just looking for a change in this particular method, well, then I'd just go with the solution you already mentioned yourself. Go ahead and refactor each repeating paragraph into a method.

From:

var parameterOne = theCmd.CreateParameter();
parameterOne.ParameterName = "@one";
parameterOne.Value = "text";
theCmd.Parameters.Add(parameterOne);

Into (for example):

private void addParameter(IDbCommand theCmd, string paramName, string paramValue )
{
    var createdParameter = theCmd.CreateParameter();
    createdParameter.ParameterName = paramName;
    createdParameter.Value = paramValue ;
    theCmd.Parameters.Add(createdParameter);
}

Also, when calling the mmethod, I prefer defining some constants for the parameter names instead of writing the string each time again. This spares me of spelling mistakes.

Define them in an appropriate scope, like as class members, if you use them in more than this method (which I guess will sure be the case).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top