I have a DataAccessBase class with the following 2 data access methods. One for ExecuteScalar and one for ExecuteNonQuery. Is it possible to consolidate it into one generic method or is even worth worrying about?
protected static int ExecuteNonQuery(SqlCommand command)
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
command.Connection = connection;
SqlDataAdapter da = new SqlDataAdapter(command);
command.Connection.Open();
int result = command.ExecuteNonQuery();
return result;
}
}
protected static string ExecuteScalar(SqlCommand command)
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
command.Connection = connection;
SqlDataAdapter da = new SqlDataAdapter(command);
command.Connection.Open();
string result = command.ExecuteScalar().ToString();
return result;
}
}
private static DataTable GetDT(int id)
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
string query = "select id, userid, name from tasks where id = @id";
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
//Parameterized query to prevent injection attacks
command.Parameters.AddWithValue("id", id);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
You can definitely avoid the current repetition you've got with a generic method, but I wouldn't try to reduce it to a single method. Here's what I'd potentially do:
protected static int ExecuteNonQuery(SqlCommand command) =>
ExecuteCommand(command, cmd => cmd.ExecuteNonQuery());
protected static string ExecuteScalar(SqlCommand command) =>
ExecuteCommand(command, cmd => cmd.ExecuteScalar().ToString());
private static T ExecuteCommand<T>(SqlCommand command, Func<SqlCommand, T> resultRetriever)
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
command.Connection = connection;
command.Connection.Open();
return resultRetriver(command);
}
}
For the DataTable
one, following the same pattern you'd create the command first:
protected static DataTable GetDataTable(SqlCommand command) =>
ExecuteCommand(cmd =>
{
SqlDataAdapter da = new SqlDataAdapter(cmd)
DataTable table = new DataTable();
da.FillTable(table);
return table;
});
See more on this question at Stackoverflow