Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Lambda expression tree parameters

$
0
0

I am trying to understand how lambda expression trees works.

Here is a sample of code:

Expression<Func<Table1,bool>> left =(x => x.email.Contains("valeur1"));Expression<Func<Table1,bool>> right =(x => x.email.Contains("valeur2"));var body =Expression.OrElse(left.Body, right.Body.Replace(right.Parameters[0], left.Parameters[0]));varwhere=Expression.Lambda<Func<Table1,bool>>(body, left.Parameters[0]);

         dbcontext.Table1.Where(where).Count());

This produce me this SQL query:

      SELECT COUNT(*)
      FROM [Table1] AS [x]
      WHERE (CHARINDEX(N'valeur1',[x].[email])>0) OR (CHARINDEX(N'valeur2',[x].[email])>0)

This is great because it is exactly what i want.

But this need this 2 extensions:

publicclassExtensions{publicstaticExpressionReplace(thisExpression expression,Expression source,Expression target){returnnewExpressionReplacer{Source= source,Target= target }.Visit(expression);}publicclassExpressionReplacer:ExpressionVisitor{publicExpressionSource;publicExpressionTarget;publicoverrideExpressionVisit(Expression node){return node ==Source?Target:base.Visit(node);}}}

I do not understand why i cannot do something like that:

Expression<Func<Table1,bool>> left =(x => x.email.Contains("valeur1"));Expression<Func<Table1,bool>> right =(x => x.email.Contains("valeur2"));var body =Expression.OrElse(left.Body, right.Body);varwhere=Expression.Lambda<Func<Table1,bool>>(body, left.Parameters[0]);

         dbcontext.Table1.Where(where).Count());

And this code doesn't work. And i want to understand why. As you can see, in my two expressions, i am using "x" parameter. So why should i have to replace ?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>