title: Where Predicates in LINQ
body: <p>How can I specify conditions in Where predicates in LINQ without getting null reference exceptions. For instance, if <code>q</code> is an IQueryable how can I do like:</p>
  
  <pre><code>Expression&lt;Func&lt;ProductEntity,bool&gt;&gt; predicate = p =&gt; !search.CategoryId.HasValue || (search.CategoryId.HasValue &amp;&amp; search.CategoryId == p.CategoryId);
  
  var q2 = q.Where(predicate);
  </code></pre>
  
  <p>Here <code>search</code> is an object that holds possible search conditions that may or may not be set like search.CategoryId might not be set but if it is I want to get the products that are set by that condition.</p>
  
  <p>When I do this I get null reference exceptions.</p>