I have the following LINQ-to-Entities query
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() }
that runs against this schema
Table P Table R Table Q
PK*
RK ----> RK*
Text QK ------> QK*
Text Text
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."
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.
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.
I tried changing my query to look like the one in Group and Count in Linq issue, but I just got a different message.
I also looked at Group and Count in Entity Framework (and a number of others) but the problem is different.
group Key can't be null
var results = ctx.Rs.Where(r => r.QK != null)
.GroupBy(r => r.QK)
.Select(gr => new { Key = (int)gr.Key, Count = gr.Count() }
.ToList();
PS.
Mostly, You don't need 'JOIN' syntax in Entity Framework. see: Loading Related Entities
Writing descriptive-meaningful variable names would significantly improve Your codes and make it understandable. Readability does matter in real world production.
I'm having trouble reading your format. But can you try:
from r in ctx.Rs
join p in ctx.Ps.DefaultIfEmpty() on r.RK equals p.RK
group r by r.QK into gr
select new { QK = (int)gr.Key, Num = gr.Count(x => x.RK != null) }
With DefaultIfEmpty
and x => x.RK != null
being the changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With