views:

259

answers:

2

How can I write a linq to entities query that includes a having clause?

For example:

SELECT State.Name, Count(*) FROM State
INNER JOIN StateOwner ON State.StateID = StateOwner.StateID
GROUP BY State.StateID
HAVING Count(*) > 1
+7  A: 

Any reason not to just use a where clause on the result?

var query = from state in states
            join stateowner in stateowners
              on state.stateid equals stateowner.stateid
            group state.Name by state.stateid into grouped
            where grouped.Count() > 1
            select new { Name = grouped.Key, grouped.Count() };
Jon Skeet
A good answer, but I would suggest grouped.Any()
Craig Stuntz
Dammit Jon.... haha... you win again! <3
womp
grouped.Any() would be used for Count() > 0, not Count() > 1
Lucas
@Craig: If it had been `Count() > 0` then there'd be no need for a restriction at all, given that it was an inner join...
Jon Skeet
I agree. Mea culpa.
Craig Stuntz
+2  A: 

I believe you can use a GroupBy followed by a Where clause and it will translate it as a Having. Not entirely sure though.

Andrew Flanagan