LINQ to Entities group by and Count()

c# count entity-framework group-by linq

Question

What I have is this using LINQ-to-Entities

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() }

it contradicts this framework

Table P  Table R   Table Q
 PK*
 RK ----> RK*
 Text     QK ------> QK*
          Text       Text

and sends the following message if any entry in Q does not have a corresponding record in P: "The materialized value is null, hence the cast to value type "Int32" failed. The query must utilize a nullable type, or the generic parameter of the result type must."

The last line's gr.Count() is the issue, but I can't figure out how to fix it. I've looked for a means to test gr for null, but I can't.

I've seen a lot of solutions to problems like mine that use Sum() rather than Count(), but I haven't been able to apply them to my situation.

I attempted to modify my query so that it resembled the one in Issue with Group and Count in Linq, but I only received a different message.

I also had a look at Entity Framework's Group and Count (as well as a few other ones), but the issue is different.

1
8
5/23/2017 11:54:35 AM

Popular Answer

ZZZ_tmp
17
1/23/2013 4:57:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow