I have a form in which the user will choose the following from dropdown lists: table_name columnName_to_sort_by columnName_to_search_in The user shall enter Search_text in a text box
The form shall draw data from many tables. I want to avoid writing the sort and search for every field for each of the tables. This is why I want to use Expression trees. I want to build the query dynamically
I want to write a generic method that will generate the Expression tree for the select, where and orderby methods, depending on user input. I can use System.Reflection to get the Type that is being querried. (All my tables are Types - I am using LinqToSql) I do not know how to form the expression trees.
Here's what I have so far:
private static List<T> GetSortedData<T>( string sortColumnName)
{
var type = typeof(T);
var property = type.GetProperty(sortColumnName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, WHAT_SHOULD_BE_HERE, Expression.Quote(orderByExp));
return (List<T>)Expression.Lambda(resultExp).Compile().DynamicInvoke();
}
How can I implement select, sort and orderby dynamically using expression trees?