I'm building a program where users can build reports by selecting fields and search criteria that they want included in the report. These fields/criteria are then used to form a query and pull the relevant data from my database.
There are many different fields and search criteria, and more can possibly be added. I've never used expression tress, but have been reading up on them, and thought this would be a good place to use them so I can dynamically build a query to get the data I need.
Right now, I have two methods written. In GetPredicateEqual, I can pass in a table with a column name and a value and get back the expression to get the correct results. GetSelector is similar but it returns an expression to use to select a certain column from the results.
This is my code:
public static void BuildThePredicate()
{
var equals = ExpressionType.Equal;
using (DataContext dc = new DataContext)
{
Expression<Func<ProductContent, bool>> predicate = GetPredicateEqual<ProductContent>("ContentId", (Int32)1, equals);
Expression<Func<ProductContent, string>> selector = GetSelector<ProductContent, string>("ProductTitle");
var query = dc.ProductContent.Where(predicate);
var query2 = dc.ProdutContent.Where(predicate).Select(GetSelector<ProductContent, string>("ProductTitle"));
}
}
public static Expression<Func<TEntity, bool>> GetPredicateEqual<TEntity>(string fieldName, long id, ExpressionType op)
{
PropertyInfo pi = typeof(TEntity).GetProperty(fieldName);
ParameterExpression lhsParam = Expression.Parameter(typeof(TEntity), "x");
Expression lhs = Expression.Property(lhsParam, pi);
Expression rhs = Expression.Constant(Convert.ChangeType(id, pi.PropertyType));
var binary = Expression.MakeBinary(op, lhs, rhs);
var lambda = Expression.Lambda<Func<TEntity, bool>>(binary, lhsParam);
return lambda;
}
public static Expression<Func<T, TReturn>> GetSelector<T, TReturn>(string fieldName)
{
ParameterExpression p = Expression.Parameter(typeof(T), "x");
var body = Expression.Property(p, fieldName);
return Expression.Lambda<Func<T, TReturn>>(body, new ParameterExpression[] { p });
}
My question is, how could I do something similar to join two(or more) tables? I've been googling and can't find any examples of how to do this.