title: Expression.Lambda: Variable 'x' of type '' referenced from scope '', but it is not defined
body: <p>I saw connected <a href="https://stackoverflow.com/questions/6106283/memberexpression-invalidoperationexpression-variable-x-referenced-from-scope">topic</a> but...</p>
  
  <p>I was attempting to implement specification pattern. If I create the Or or And Expression explicitly with the <code>System.Linq.Expressions</code> API, I will get the error </p>
  
  <blockquote>
    <p>InvalidOperationExpression variable 'x' referenced from scope.</p>
  </blockquote>
  
  <p>For example ,this is my code</p>
  
  <pre><code>public class Employee
  {
      public int Id { get; set; }
  }
  
  Expression&lt;Func&lt;Employee, bool&gt;&gt; firstCondition = x =&gt; x.Id.Equals(2);
  Expression&lt;Func&lt;Employee, bool&gt;&gt; secondCondition = x =&gt; x.Id &gt; 4;
  
  
  Expression predicateBody = Expression.OrElse(firstCondition.Body, secondCondition.Body);
  Expression&lt;Func&lt;Employee, bool&gt;&gt; expr = 
      Expression.Lambda&lt;Func&lt;Employee, bool&gt;&gt;(predicateBody, secondCondition.Parameters);
  Console.WriteLine(session.Where(expr).Count()); - //I got error here
  </code></pre>
  
  <p>EDITED </p>
  
  <p>I tried to use <a href="http://www.adamaldrich.com/blog/post/Specification-Pattern-and-Linq.aspx" rel="nofollow noreferrer">Specification pattern with Linq to Nhibernate</a> so in a my work code it looks like: </p>
  
  <pre><code>ISpecification&lt;Employee&gt; specification = new AnonymousSpecification&lt;Employee&gt;(x =&gt; x.Id.Equals(2)).Or(new AnonymousSpecification&lt;Employee&gt;(x =&gt; x.Id &gt; 4));
  var results = session.Where(specification.is_satisfied_by());
  </code></pre>
  
  <p>So I want to use code like this x => x.Id > 4. </p>
  
  <p>Edited</p>
  
  <p>So my solution is    </p>
  
  <pre><code> InvocationExpression invokedExpr = Expression.Invoke(secondCondition, firstCondition.Parameters);
  var expr = Expression.Lambda&lt;Func&lt;Employee, bool&gt;&gt;(Expression.OrElse(firstCondition.Body, invokedExpr), firstCondition.Parameters);
  Console.WriteLine(session.Where(expr).Count());
  </code></pre>
  
  <p>Thank you @Jon Skeet</p>