Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Lambda Expression inside an Expression Query

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.

like image 362
Kamyar Nazeri Avatar asked Dec 05 '25 05:12

Kamyar Nazeri


2 Answers

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.

like image 58
Vladislav Zorov Avatar answered Dec 07 '25 17:12

Vladislav Zorov


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

like image 25
NateTheGreat Avatar answered Dec 07 '25 19:12

NateTheGreat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!