I have a WPF
application (using MVVM
pattern) that allows users to perform a search for a record/records based on their selection choices and entries into the different UI controls (TextBox
, CheckBox
, RadioButton
, DatePicker
, TimerPicker,
etc). It does this by retrieving information from an Access
database.
I have an Access
query method in my AccessWorker
class that looks like this (note that this is simplified a bit, because I can't post everything I have):
public DataSet GetRecords(string customQuery = "")
{
var data = new DataSet();
try
{
using (var con = new OleDbConnection(ConnectionString))
{
string queryString = "SELECT * FROM Records " + customQuery;
using (var da = new OleDbDataAdapter(queryString, con))
{
da.Fill(data, "Records");
}
}
}
catch (Exception e)
{
ExceptionLogger.Record(e.Message);
}
return data;
}
As you can see, I pass a custom query argument to this method in a form of a string
. I construct this query string using a StringBuilder
in my ViewModel
and then I pass it to GetRecords()
method. Here's the GetQueryString()
method that does the string building:
private string GetQueryString()
{
var query = new StringBuilder();
if (!String.IsNullOrWhiteSpace(RecNumber))
{
query.Append("Record_Number = '" + RecNumber + "'");
}
if (!String.IsNullOrWhiteSpace(EmployeeId))
{
if (!String.IsNullOrWhiteSpace(query.ToString()))
{
query.Append(" AND ");
}
query.Append("Employee_ID LIKE '%" + EmployeeId + "%'");
}
if (!String.IsNullOrWhiteSpace(Location))
{
if (!String.IsNullOrWhiteSpace(query.ToString()))
{
query.Append(" AND ");
}
query.Append("Location LIKE '%" + Location + "%'");
}
if (!String.IsNullOrWhiteSpace(FirstName))
{
if (!String.IsNullOrWhiteSpace(query.ToString()))
{
query.Append(" AND ");
}
query.Append("First_Name LIKE '%" + FirstName + "%'");
}
if (!String.IsNullOrWhiteSpace(LastName))
{
if (!String.IsNullOrWhiteSpace(query.ToString()))
{
query.Append(" AND ");
}
query.Append("Last_Name LIKE '%" + LastName + "%'");
}
//...and so on...
return String.Format("WHERE {0}", query.ToString());
}
The above method is severely shortened here so that I wouldn't have to post a very long wall of code, but I'm dealing with 25 different controls and so there could be a condition for everyone of them that would have to be part of this query string. The method itself, as you can imagine, is rather too large by anyone's standard. When I took a C++ class in college, my instructor told me that if I can help it, I should keep my methods no longer than what I can see on the screen. I'm bowing my head in shame... heh
I don't believe that this is the most elegant way of accomplishing this task. Unfortunately, I haven't come up with a better approach. I do my best at trying to learn new patterns every day, but I've been programming for under a year and a half, so any guidance would be greatly appreciated.
By the way, based on some of the comments, I have to clear up that I'm using properties that are bound to control, not controls' values....