Entity Framework T-Sql “having” Equivalent

风流意气都作罢 提交于 2019-12-17 20:04:38

问题


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

回答1:


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



回答2:


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




回答3:


If you want to compare a variable that is not in the group by (Ex: age), then it would be:

var duplicated = (
                  from q1 in db.table1
                  where (q1.age >= 10 )
                  group q1 by new { q1.firstName, q1.lastName } into grp
                  where (grp.Count() > 1 )
                  select new 
                   {
                     firstName= grp.Key.firstName,
                     lastName = grp.Key.lastName,
                   }
                 );


来源:https://stackoverflow.com/questions/1406962/entity-framework-t-sql-having-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!