How to make C# code using ADO.NET, IDbConnection and IDbCommand less verbose?

Michael Low picture Michael Low · Nov 11, 2011 · Viewed 9.1k times · Source

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();
 }

Answer

Felice Pollano picture Felice Pollano · Nov 11, 2011

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