How to create dynamic condition using Expression Tree

c# c#-4.0 entity-framework expression-trees linq

Question

Please consider this code:

System.Linq.Expressions.Expression<Func<tbl, bool>> exp_details = r => r.ID_Master == Id &&
r.Year == Year &&
r.Month == Month ;

I want to write a function that expect some argument, and then retrieve some data from my database. The problem is I want to create dynamic condition.dor example if I pass IsDeleted argument with true value I want to add r.IsDeleted == true; to exp_details. How can I do this?

Accepted Answer

The key to doing this is to use an ExpressionVisitor which walks the given expression and (optionally, in a subclass) allows for replacing recognized elements with others you specify. In my case this was done for ORM (NHibernate). This is what I use: (I'll add references to my answer later)

public class ParameterAssignAndReplacer : ExpressionVisitor
{
    private readonly ParameterExpression _source;
    private readonly ConstantExpression _target;

    internal ParameterAssignAndReplacer(ParameterExpression source, ConstantExpression target)
    {
        _source = source;
        _target = target;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        return node.Name == _source.Name ?
            base.VisitConstant(_target) :
            base.VisitParameter(node);
    }
}

And..

public static class ExpressionExtensions
{
    public static Expression<Func<TArg2, TResult>> AssignAndReduce<TArg1, TArg2, TResult>(
        this Expression<Func<TArg1, TArg2, TResult>> func,
        TArg1 parameter)
    {
        var exprBody = func.Body;
        var assignedParameter = Expression.Constant(parameter, typeof(TArg1));
        exprBody = new ParameterAssignAndReplacer(func.Parameters[0], assignedParameter).Visit(exprBody);
        return Expression.Lambda<Func<TArg2, TResult>>(exprBody, func.Parameters[1]);
    }
}

Both classes can be extended to your specific scenario. To make this relevant to the code you posted (I'm using only IsDeleted as the parameter for simplicity):

public class SomeClass
{
    Expression<Func<tbl, bool, bool>> _templateExpression =
       (tbl r, bool isDeleted) => r.ID_Master == 5 && r.Year == 2008 && r.Month == 12 && r.IsDeleted == isDeleted;

    public Expression<Func<tbl, bool>> Foo(bool IsDeleted)
    {
        return _templateExpression.AssignAndReduce(IsDeleted);
    }
}

Regarding references, most of what I learned on this topic is from Marc Gravell's "Expressions" answers [ although many other users have helped me get a grip on this :-) ]


Popular Answer

you can't use statement body to Linq Expression consider using Predicate instead

        var exp_details = new Predicate<tbl>(r =>
        {
            bool result == Id && r.Year == Year && r.Month == Month;
            if(IsDeleted != null)
            {
                result &= r.IsDeleted == IsDeleted;
            }
            return result;
        });

the most Linq Func<T, bool> expression can be replaced with Predicate<T>.

To generate dynamic WHERE cause using "simple" linq expression.

IQueryable<tbl> query = ent.tbl.Where(r => r.ID_Master == Id && r.Year == Year);
//customize query
if(IsDeleted != null){
  query = query.Where(r => r.IsDeleted == IsDeleted);
}
//execute the final generated query
var result = query.FirstOrDefault();

this will create where cause from IQueryable<T>. Linq is smart enough for complex query.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why