From a previous question, I got the idea of moving boilerplate code structures into a helper function and passing in a lambda function to it.
I then applied the idea to a data access class (code below). I'm not sure how to handle the result of my ProcessDatabaseCall
helper function; it seems irrelevant to my pattern of use-cases. In this example I'm returning an IEnumerable
; in other cases I'm returning int
, School
, etc.
public IEnumerable<School> SchoolsList(string searchChars)
{
DataSet ds = new DataSet();
List<School> schools = new List<School>();
bool cool = ProcessDatabaseCall("dbo.usp_esrvs_API_SchoolList", cmd => {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return true;
});
//Foreach row in the data set add a json array object
foreach (DataRow row in ds.Tables[0].Rows)
{
schools.Add(new School((int) row["esrvs_Account_ID"], row["SchoolName"].ToString()));
}
return schools;
}
private bool ProcessDatabaseCall(string procedureName, Func<SqlCommand,bool> processor)
{
using (SqlConnection Mackin1Conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(procedureName, Mackin1Conn))
{
return processor(cmd);
}
}
}
The function used to look like this:
public IEnumerable<School> SchoolsList(string searchChars)
{
DataSet ds = new DataSet();
List<School> schools = new List<School>();
using (SqlConnection Mackin1Conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.usp_esrvs_API_SchoolList", Mackin1Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SearchValue", searchChars));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
}
foreach (DataRow row in ds.Tables[0].Rows)
{
schools.Add(new School((int) row["esrvs_Account_ID"], row["SchoolName"].ToString()));
}
return schools;
}