title: LINQ join on columns AND nullable variable
body: <p>I am trying to join tables using LINQ by matching columns where a column in the joined table is equal to a variable or the variable is null (at which point the join still needs to happen just not on that field).</p>
  
  <p>My LINQ is something like:</p>
  
  <pre><code>var data = (
      from lt in cxt.CmsPageRow
      join page in cxt.CmsPage on new { lt.CmsPageID, cmsSiteID.Value } equals new { page.CmsPageID, page.CmsSiteID }
      ...
  </code></pre>
  
  <p>cmsSiteID is a nullable INT.</p>
  
  <p>I cannot compile my code as it is complaining about "Type inference failed in the call to 'Join'."</p>
  
  <p>On top of that I need to only join on page.CmsSiteID when cmsSiteID is not null. If cmsSiteID is null then the join on lt.CmsPageID still needs to happen.</p>
  
  <p><strong>* EDIT *</strong></p>
  
  <p>The question has kind of changed now. I can get it to do what I want by using a WHERE clause on the join in my LINQ.</p>
  
  <pre><code>join page in cxt.CmsPage.Where(p=&gt;(cmsSiteID==0||p.CmsSiteID==cmsSiteID)) on lt.CmsPageID equals page.CmsPageID
  </code></pre>
  
  <p>However, this still runs slow. If I change the parameter passed through to a literal it executes instantly.</p>
  
  <p>Slow runner</p>
  
  <pre><code>(@p__linq__1 = 0 OR [Extent2].[CmsSiteID] = @p__linq__1)
  </code></pre>
  
  <p>Fast runner</p>
  
  <pre><code>(267 = 0 OR [Extent2].[CmsSiteID] = 267)
  </code></pre>
  
  <p>Is there a way to speed this up?</p>