title: How to declare a Linq Expression variable in order to have it processed as a dbParameter
body: <p>I'm trying to create dynamic queries against Entity framework (or other Linq provider).</p>
  
  <p>Let me explain my problem with some sample code.</p>
  
  <p>If I hardcode an expression :</p>
  
  <pre class="lang-cs prettyprint-override"><code>var id = 12345;
  
  Expression&lt;Func&lt;ItemSearch, bool&gt;&gt; myLambda = (s) =&gt; s.Id == id;
  
  var finalQuery = context.ItemSearch.Where(myLambda);
  this.Log((finalQuery as ObjectQuery).ToTraceString());
  </code></pre>
  
  <p>The generated SQL looks like this :</p>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT ...
  FROM ViewItemSearch "Extent1"
  WHERE "Extent1".ID = :p__linq__0
  </code></pre>
  
  <p>with a nice <code>:p__linq__0</code> dbParameter.</p>
  
  <p>If I create an expression :</p>
  
  <pre class="lang-cs prettyprint-override"><code>var id = 12345;
  ParameterExpression param = Expression.Parameter(typeof(ItemSearch), "s");
  Expression prop = Expression.Property(param, "Id");
  Expression val = Expression.Constant(id);
  Expression searchExpr = Expression.Equal(prop, val);
  
  Expression&lt;Func&lt;ItemSearch, bool&gt;&gt; myLambda =  
      Expression.Lambda&lt;Func&lt;ItemSearch, bool&gt;&gt;(searchExpr , param);
  
  var finalQuery = context.ItemSearch.Where(myLambda);
  this.Log((finalQuery as ObjectQuery).ToTraceString());
  </code></pre>
  
  <p>The generated SQL looks like this :</p>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT ...
  FROM ViewItemSearch "Extent1"
  WHERE "Extent1".ID = 12345
  </code></pre>
  
  <p>No more <code>:p__linq__0</code> dbParameter so the Db engine cannot cache query plans.</p>
  
  <p>I understand that it is because I use </p>
  
  <pre class="lang-cs prettyprint-override"><code>Expression val = Expression.Constant(id);
  </code></pre>
  
  <p>But I can't figure out how to bind a variable instead of the value.</p>