3

Is it possible to use a dynamic Linq Expression inside a Query Expression? Something like this:

from obj1 in ObjectSet1
let res = ObjectSet2.Where(* SomeExpression *)
where ...
select ...

I'm trying to build Expression.Lambda<Func<TSource, bool>> Expression as for SomeExpression.

  1. Is it possible to to use dynamic Linq Expression within the Expression Query or do I need to build the whole Expression tree from scratch?
  2. How can I, if any, use obj1 when I'm building SomeExpression?

Note: I'm using Entity Framework, I can't use SomeExpression.Compile() within the expression tree.

2
  • I believe it is. Look here for more info (weblogs.asp.net/scottgu/archive/2008/01/07/…) and here (naspinski.net/post/…) Commented Mar 12, 2012 at 20:31
  • Thanks, string predicate might help! I was wondering if it is possible to use the Expression builder? Expression.Parameter(typeof(TSource), "obj1") doesn't seem to work! Commented Mar 12, 2012 at 20:36

2 Answers 2

3

It's not only possible, it's normal. Large expression trees can be generated from smaller trees (this is what LINQ does). You only have to pass in an Expression<Func<TSource, bool>> to Where().

You can see how in my reply to this other thread here - replacing operator in Where clause Lambda with a parameter . The interesting part is in the MakeWhereLambda method.

Sign up to request clarification or add additional context in comments.

2 Comments

Alright, how to use the query iterator inside the expression? I need to have access to obj1 (from above sample) in the new Expression. How do you define the ParameterExpression?
Hmmm... can't you just refer to it normally? Isn't it in your scope? P.S. It's not part of your expression as it's neither input nor output. It's a so called free variable.
1

If you're wanting it to be completely dynamic, one possible option would be to use Expression Tree Serialization:

http://expressiontree.codeplex.com/

I started to use this a while back but that task got reprioritized, so I'm not sure how suitable it is for any given task. That said, it looks pretty good...

Hope this helps.

Nate

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.