title: LINQ to Entities group by and Count()
body: <p>I have the following LINQ-to-Entities query</p>
  
  <pre><code>from r in ctx.Rs
  join p in ctx.Ps on r.RK equals p.RK
  group r by r.QK into gr
  select new { QK = (int)gr.Key, Num = gr.Count() }
  </code></pre>
  
  <p>that runs against this schema</p>
  
  <pre><code>Table P  Table R   Table Q
   PK*
   RK ----&gt; RK*
   Text     QK ------&gt; QK*
            Text       Text
  </code></pre>
  
  <p>and gives this message if there is any record in Q with no corresponding record in P: "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."</p>
  
  <p>The problem is the gr.Count() in the last line, but I cannot find a solution.  I have tried to test gr for null, but cannot find a way that works.</p>
  
  <p>I have seen a number of solutions to a similar problem using Sum() instead of Count(), but I have not been able to adapt them to my problem.</p>
  
  <p>I tried changing my query to look like the one in <a href="https://stackoverflow.com/questions/12573785/group-and-count-in-linq-issue">Group and Count in Linq issue</a>, but I just got a different message.</p>
  
  <p>I also looked at <a href="https://stackoverflow.com/questions/13012472/group-and-count-in-entity-framework">Group and Count in Entity Framework</a> (and a number of others) but the problem is different.</p>