Let's say that i have a database which contain cheese. I love cheese. Depending on the request my server is getting (c# WebApi), i have to filter user data accordingly. Maybe the user wants to only get cheese up to a certain date, or from a certain date, or between to dates. Maybe he wants all french cheese, or american cheese. My model works, but i dont like switchs, and i feel like there is a better way.
The model is as follow :
namespace myAPI.Models
{
public enum CheeseFilter
{
Country,
DateFrom,
DateStart,
DateBetween,
};
public class FilterQuery
{
public CheeseFilter? filter { get; set; }
public DateTime? DateStart{ get; set; }
public DateTime? DateEnd{ get; set; }
public String Country{ get; set; }
}
}
This model is what's get filled [FromPost]
Now, i'm creating a tuple which will hold the StoredProcedure name (Basically, a select with where, order by, etc), its parameters, and the choosen filter, like so :
private Tuple<CheeseFilter, String, List<SqlParameter>> LoadedCheeseWithOptions;
And where i actually fill it :
public bool CheeseFilterTuple()
{
bool flag = false;
List<SqlParameter> options = new List<SqlParameter>();
String SPName = "ERROR";
DateTime tmp = new DateTime(); // ForChecking GoodFormating of datetimes
DateTime tmp2 = new DateTime();
switch (GetMode().Value)
{
case CheeseFilter.DateFrom:
flag = !String.IsNullOrWhiteSpace(dateStart) && DateTime.TryParseExact(dateStart, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);;
options.Add( new SqlParameter() { Name = "@DateStart", Value = tmp.ToString("yyyyMMdd")});
SPName = "Cheese_FromDate";
break;
case CheeseFilter.DateStart:
flag = !String.IsNullOrWhiteSpace(dateEnd) && DateTime.TryParseExact(dateEnd, TMP_DATEFORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out tmp);
options.Add(new SqlParameter() { Name = "@DateEnd", Value = tmp.ToString("yyyyMMdd") });
SPName = "Cheese_To_Date";
break;
case CheeseFilter.BetweenDates:
flag = !String.IsNullOrWhiteSpace(dateStart) && DateTime.TryParse(dateStart, out tmp) && !String.IsNullOrWhiteSpace(dateEnd) && DateTime.TryParse(dateEnd, out tmp2);
options.Add( new SqlParameter() { Name = "@DateStart",Value = tmp.ToString("yyyyMMdd")}); //Converting for sqlServer
options.Add( new SqlParameter() { Name = "@DateEnd", Value = tmp2.ToString("yyyyMMdd")});
SPName = "Cheese_Between_Date";
break;
}
LoadedCheeseWithOptions = new Tuple<CheeseFilter, string, List<SqlParameter>>(GetMode().Value, SPName, options);
return flag;
}
GetMode()
is just transforming the CheeseFilter?
into a CheeseFilter.
The main issue is that, with this last bit of code here, i feel like with every new filter that I might get asked to create will mean adding another block of code to the pile, which I think is a poor man's solution.
So I'm asking you for some guidelines, or even better ways that'd you handle better this optional filter loading.