Search code examples
c#linqentity-frameworkexpression-trees

How to create where clause only by Expression


What I want to achieve is a simple where clause with expression tree (only):

Tags.Where(t => t.Title == "Exam")

what i have done so far :

ParameterExpression pe = Expression.Parameter(typeof(EfTag), "t");
Expression left = Expression.Property(pe, typeof(EfTag).GetProperty("Title"));
Expression right = Expression.Constant("Exam");
Expression e1 = Expression.Equal(left, right);

var neededTags = myDataContext.Tags.where( e1 /* what should i do here WI?? */ );

Please do not refer me to System.Linq.Dynamic or LinqKit. i need to do this without using any Third part library.


Solution

  • You're almost there. Now that you have the parameter and == operator call, you have to combine them together into a Lambda:

    var predicate = Expression.Lambda<Func<EfTag, bool>>(e1, pe);
    

    You can later on use it in Where call:

    var neededTags = myDataContext.Tags.Where(predicate);