如何仅在EF中的列上使用count

时间:2016-07-26 17:23:00

标签: c# sql sql-server entity-framework linq

我想在ef中使用该查询:

 select count(number) as CountOfNumber ,number, name  from table_1 group by number, name order by CountOfNumber desc

如何在列上使用count并添加此列的新名称。

2 个答案:

答案 0 :(得分:3)

您需要使用GroupByOrderByCount组合:

var results = (from item in db.table_1
                group item by new { item.name, item.number } into grouping
                orderby grouping.Count() descending
                select new
                {
                    name = grouping.Key.name,
                    number = grouping.Key.number,
                    CountOfNumber = grouping.Count()
                }).ToList();

答案 1 :(得分:0)

https://msdn.microsoft.com/en-us/library/bb545971.aspx

您可以在群组中使用Count方法。 context是您的实体框架数据上下文或任何IEnumerable

 var results = from t in context.table_1
               group t by new { t.number, t.name } into g
               orderby g.Count() descending
               select new { number = g.Key.number, name = g.Key.name, count = g.Count() };