Home > Enterprise >  Building a Lambda Expression with Where Clause on multiple joined tables?
Building a Lambda Expression with Where Clause on multiple joined tables?

Time:10-05

I have to add a .Where() clause on the db1 table in my LINQ query that looks something like this:

var query = from db1 in db.db1
                              join db2 in db.database2 on db1.atr1 equals db2.atr1
                              join db3 in db.database3 on db1.atr1 equals db3.atr1
                              select new { db1, db2, db3};

I have added a Lambda expression to a query where there is not the join clause, but can't figure out when you have these "nested" tables. Instead of:

query = query.Where(t => t.attr5.Contains("String"));

It would have to be:

query = query.Where(t => t.db1.attr5.Contains("String"));

My code to build the lambda for the Where() looks like this:

ParameterExpression eParam = Expression.Parameter(tableType, "innerTable");
MethodInfo method = filterValue.GetType().GetMethod("Contains", new Type[] { typeof(string) }); // filterValue is just a string
MethodCallExpression call = Expression.Call(Expression.Property(eParam, filterField), method, Expression.Constant(filterValue));
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, eParam);
currentQuery = currentQuery.Where(lambda);

tableType is a variable where I get the PropertyType for a table with the select new statement, but it will throw and error since it doesn't match the object select new { db1, db2, db3 }.

I am assuming I need to make another:

ParameterExpression eParam = Expression.Parameter(typeof(T), "item");? and somehow . that before the MethodCallExpression, not sure though.

CodePudding user response:

I figured this out. I had to take from this answer:

https://stackoverflow.com/a/18896870/6368685

But I am not using:

var lambdaExpression = Expression.Lambda(expression, parameter);
return lambdaExpression;

Instead, I take the expression variable and pass it into the MethodCallExpression I need to build before building the lambda:

MethodInfo method = filterValue.GetType().GetMethod("Contains", new Type[] { typeof(string) });
MethodCallExpression call = Expression.Call(expression, method, Expression.Constant(filterValue));
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, argLambda);
currentQuery = currentQuery.Where(lambda);
  • Related