I am working on a dynamic query solution for a project. I want to avoid a bunch of if/else or switch statements just to change the [DynamicFieldName] part of these queries.
IQueryable<MyDataType> allItems = (from item in Context.MyDataTypes select item);
foreach (QueryEntry currentEntry in query.Fields)
{
allItems = allItems.Where(item => item.[DynamicFieldName] == currentEntry.Value);
}
The user gets to build the query via the GUI that has a variable number of fields. In the end, they will also have a variety of comparisons to choose from (Less than, greater than, equal, contains, etc.) that vary by data type.
What method can I use to build this programatically in a nice reusable fashion?
Have a look at this code:
public static class CustomQueryBuilder
{
//todo: add more operations
public enum Operator
{
Equal = 0,
GreaterThan = 1,
LesserThan = 2
}
public static IQueryable<T> Where<T>(this IQueryable<T> query, string property, Operator operation, object value)
{
//it's an item which property we are referring to
ParameterExpression parameter = Expression.Parameter(typeof(T));
//this stands for "item.property"
Expression prop = Expression.Property(parameter, property);
//wrapping our value to use it in lambda
ConstantExpression constant = Expression.Constant(value);
Expression expression;
//creating the operation
//todo: add more cases
switch (operation)
{
case Operator.Equal:
expression = Expression.Equal(prop, constant);
break;
case Operator.GreaterThan:
expression = Expression.GreaterThan(prop, constant);
break;
case Operator.LesserThan:
expression = Expression.LessThan(prop, constant);
break;
default:
throw new ArgumentException("Invalid operation specified");
}
//create lambda ready to use in queries
var lambda = Expression.Lambda<Func<T, bool>>(expression, parameter);
return query.Where(lambda);
}
}
Usage
var users = context
.Users
.Where("Name", CustomQueryBuilder.Operator.Equal, "User")
.ToList();
Which is equal to
var users = context
.Users
.Where(u => u.Name == "User")
.ToList();