SQL to Entity Framework Count Group-By

后端 未结 5 1674
野趣味
野趣味 2020-11-28 06:26

I need to translate this SQL statement to a Linq-Entity query...

SELECT name, count(name) FROM people
GROUP by name
5条回答
  •  生来不讨喜
    2020-11-28 06:46

    Here is a simple example of group by in .net core 2.1

    var query = this.DbContext.Notifications.
                Where(n=> n.Sent == false).
                GroupBy(n => new { n.AppUserId })
                .Select(g => new { AppUserId = g.Key, Count =  g.Count() });
    
    var query2 = from n in this.DbContext.Notifications
                where n.Sent == false
                group n by n.AppUserId into g
                select new { id = g.Key,  Count = g.Count()};
    

    Which translates to:

    SELECT [n].[AppUserId], COUNT(*) AS [Count]
    FROM [Notifications] AS [n]
    WHERE [n].[Sent] = 0
    GROUP BY [n].[AppUserId]
    

提交回复
热议问题