Ben Jones Ben Jones - 3 months ago 29
C# Question

how to use multiple parameters when combining expressions using Expression.Lambda

Ok so here's the problem I am creating an expression dynamically to execute against the database, that works fine. the problem appears when I add another expression using Expression.AndAlso, the expressions combine fine but the parameters don't work, my code is below.

Expression<Func<Invoice, bool>> condition = null;

ParameterExpression[] param = new ParameterExpression[sessionModel.FilterChildren.Count];

foreach (var filter in sessionModel.FilterChildren) {

param[i] = Expression.Parameter(typeof(Invoice), filter.SysName);

Type type = Type.GetType(filter.Type);

if (i == 0)
condition =
Expression.Lambda<Func<Invoice, bool>>(
Expression.Equal(
Expression.Property(param[i], filter.SysName),
Expression.Constant(filter.Value, type)
),
param[i]);
else {
var newCond = Expression.Lambda<Func<Invoice, bool>>(
Expression.Equal(
Expression.Property(param[i], filter.SysName),
Expression.Constant(filter.Value, type)
),
param[i]);

var test = Expression.AndAlso(condition.Body, newCond.Body);

condition = Expression.Lambda<Func<Invoice, bool>>(test, param);
}
i++;
}


it throws an error

Incorrect number of parameters supplied for lambda declaration


there are different parameters for each expression that will be added.

any ideas where i am going wrong?

Thanks

Answer

how to use multiple parameters when combining expressions using Expression.Lambda

You shouldn't be using multiple parameters. The lambda expression

Expression<Func<Invoice, bool>> condition

implies single parameter of type Invoice.

To fix the issue, replace

ParameterExpression[] param = new ParameterExpression[sessionModel.FilterChildren.Count];

with

var param = Expression.Parameter(typeof(Invoice), "invoice");

and in the rest of the code, replace param[i] with param.