title: LINQ to Entities - Left outer join with a conditional where clause
body: <p>I have this project set up with EF4 and I'm using LINQ to Entities to form queries.</p>
  
  <p>I'm having some trouble with a query that involves lots of conditional where clauses and several left outer joins.</p>
  
  <p>I have partially solved the conditional where clauses with the following extension method (which I found <a href="https://stackoverflow.com/questions/3970723/entity-framework-code-first-search-criteria">here</a>).</p>
  
  <pre><code>public static IQueryable&lt;TSource&gt; WhereIf&lt;TSource&gt;(this IQueryable&lt;TSource&gt; source, bool condition, Expression&lt;Func&lt;TSource, bool&gt;&gt; predicate)
      {
          if (condition)
              return source.Where(predicate);
          else
              return source;
      }
  </code></pre>
  
  <p>The problem I have now is that LINQ to Entities doesn't recognize the extension method when I use it on the joined tables.</p>
  
  <p>Here's a part of the query:</p>
  
  <pre><code>from p in context.Entities.OfType&lt;Patient&gt;()
      .WhereIf(!string.IsNullOrEmpty(name), p =&gt; p.Name.Contains(name))
  from c in context.Contacts
      .Where(cp =&gt; cp.EntityID == p.EntityId).DefaultIfEmpty()
      .WhereIf(timestamp != null, c =&gt; c.Timestamp &gt; timestamp)
  </code></pre>
  
  <p>I say partially solved because it works just fine the first time (patient name) in this query, but the second time (timestamp) it gives me this error:</p>
  
  <pre><code>LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[x.Contact] WhereIf[Contact](System.Linq.IQueryable`1[x.Contact], Boolean, System.Linq.Expressions.Expression`1[System.Func`2[x.Contact,System.Boolean]])' method, and this method cannot be translated into a store expression.
  </code></pre>
  
  <p>So, I'm wondering if anyone know how I can fix this?</p>