Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you're looking for optionally adding <code>AND xyz</code>, you could simply chain <code>Where</code> calls:</p> <pre><code>var projects = dataContext.Projects.Where(p =&gt; p.ProjectDescription.Contains(search)); if (isID) projects = projects.Where(p =&gt; p.ProjectID == projectID); </code></pre> <p>Unfortunately things are not so easy when you'd like to do an <code>OR xyz</code>. For this to work, you'll need to build a predicate expression by hand. <strong>It's not pretty.</strong> One way to do this is</p> <pre><code>Expression&lt;Func&lt;Project, bool&gt;&gt; predicate = p =&gt; p.ProjectDescription.Contains(search); if (isID) { ParameterExpression param = expr.Body.Parameters[0]; predicate = Expression.Lambda&lt;Func&lt;Project, bool&gt;&gt;( Expression.Or( expr.Body, Expression.Equal( Expression.Property(param, "ProjectID"), Expression.Constant(projectID))), param); } var projects = dataContext.Projects.Where(predicate); </code></pre> <p>Note that adding a condition to the existing predicate is a lot more work than creating the initial expression, because we need to completely rebuild the expression. (A predicate must always use a single parameter; declaring two expressions using lambda syntax will create two separate parameter expression objects, one for each predicate.) Note that the C# compiler does roughly the same behind the scenes when you use lambda syntax for the initial predicate.</p> <p>Note that this might look familiar if you're used to the criteria API for Hibernate, just a little more verbose.</p> <hr> <p>Note, however, that some LINQ implementations are pretty smart, so the following may also work:</p> <pre><code>var projects = dataContext.Projects.Where( p =&gt; p.ProjectDescription.Contains(search) || (isID &amp;&amp; p.ProjectID == projectID)); </code></pre> <p>YMMV, though, so do check the generated SQL.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload