johnny 5
johnny 5

Reputation: 20995

Linq Expression Building Incorrect number of parameters supplied for lambda declaration

So I'm trying to build a Generic Expression that Takes in a Datetime property from an IQueryable, and applies a Day comparison against it. However I keep getting an Error forIncorrect number of parameters supplied.

My function looks like this:

public IQueryable<T> SetDateCompare<T>(IQueryable<T> OriginalQuery, Expression<Func<T, DateTime>> getDateFunc, DateTime ComparisonDate, bool isGreaterThan = true)
    where T : class
    {
        if (isGreaterThan)
        {

            Expression left = Expression.Call(getDateFunc.Body, typeof(DateTime).GetMethod("get_Day"));
            Expression right = Expression.Constant(ComparisonDate.Day, typeof(int));
            Expression res = Expression.GreaterThan(left, right); 

           //var whereCall =  Expression.Lambda<Func<T,bool>>(Expression.GreaterThanOrEqual(left, right), ).

            MethodCallExpression whereCall = Expression.Call(typeof(Queryable), 
                                                                    "Where", 
                                                                    new Type[] { OriginalQuery.ElementType }, 
                                                                    OriginalQuery.Expression,
                                                                    Expression.Lambda<Func<string, bool>>(res), getDateFunc.Parameters.Single());

            OriginalQuery.Provider.CreateQuery<T>(whereCall);
        }

        return OriginalQuery;

    }

Does anyone know what I can do to fix this?

Upvotes: 1

Views: 767

Answers (1)

user4071723
user4071723

Reputation:

Try Fixing your code like this:

    public IQueryable<T> SetDateCompare<T>(IQueryable<T> OriginalQuery, Expression<Func<T, DateTime>> getDateFunc, DateTime ComparisonDate, bool isGreaterThan = true)
where T : class
    {
        if (isGreaterThan)
        {

            Expression left = Expression.Call(getDateFunc.Body, typeof(DateTime).GetMethod("get_Day"));
            Expression right = Expression.Constant(ComparisonDate.Day, typeof(int));
            Expression res = Expression.GreaterThan(left, right);

            var whereCallLambda = Expression.Lambda<Func<T, bool>>(Expression.GreaterThanOrEqual(left, right), getDateFunc.Parameters.Single());

            MethodCallExpression whereCall = Expression.Call(typeof(Queryable),
                                                                    "Where",
                                                                    new Type[] { OriginalQuery.ElementType },
                                                                    OriginalQuery.Expression,
                                                                    whereCallLambda);

            OriginalQuery = OriginalQuery.Provider.CreateQuery<T>(whereCall);
        }

        return OriginalQuery;

    }

Upvotes: 1

Related Questions