I have the following method which I use in multiple places, but it only differs by a few different things, so I was wondering how I can refactor it so I can have it in a common class and call it from there everywhere.
public override DataTable GetRecords(QueryContext queryContext, out int totalRecords)
{
// Build Query
//Different
StringBuilder query = new StringBuilder("SELECT * FROM TABLE");
Dictionary<string, string> parameters = new Dictionary<string, string>();
if (queryContext.OrderByColumns.Count == 0)
{
//Can very in length or number of parameters
queryContext.OrderByColumns.Add("param_1"); //different
queryContext.OrderByColumns.Add("param_2"); //different
}
if (queryContext.Parameters.Count > 0)
{
foreach (QueryParameter p in queryContext.Parameters)
{
dataAccess.paramAdd(parameters, query, p.ColumnName, p.Value.ToString());
}
}
// Order By Clause
query.Append(queryContext.OrderByColumns.GetSqlClause());
// Apply Limit
if (queryContext.ApplyLimit)
{
query.AppendFormat(" LIMIT {0},{1}", queryContext.Offset, queryContext.Limit);
}
//Execute the query.
DataSet results = dataAccess.ExecuteQuery(query.ToString(), parameters);
totalRecords = Convert.ToInt32(results.Tables[1].Rows[0][0]);
return results.Tables[0];
}
The only differences in other places are the value of the query
variable and the paramters added by queryContext.OrdByColumn.Add(...)
. Other than that, everything is the same.
My first shot was going to be doing something like:
public override DataTable GetRecords(StringBuilder query, string[] orderByParams, QueryContext queryContext, out int totalRecords)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
if (queryContext.OrderByColumns.Count == 0)
{
foreach(var param in orderByParams)
{
queryContext.OrderByColumns.Add(param);
}
}
if (queryContext.Parameters.Count > 0)
{
foreach (QueryParameter p in queryContext.Parameters)
{
dataAccess.paramAdd(parameters, query, p.ColumnName, p.Value.ToString());
}
}
// Order By Clause
query.Append(queryContext.OrderByColumns.GetSqlClause());
// Apply Limit
if (queryContext.ApplyLimit)
{
query.AppendFormat(" LIMIT {0},{1}", queryContext.Offset, queryContext.Limit);
}
//Execute the query.
DataSet results = dataAccess.ExecuteQuery(query.ToString(), parameters);
totalRecords = Convert.ToInt32(results.Tables[1].Rows[0][0]);
return results.Tables[0];
}
LINQ is available to me, so if that can improve it, I am welcome to ideas using that too.