我需要将此SQL
语句转换为Linq-Entity
查询...
SELECT name, count(name) FROM people
GROUP by name
我需要将此SQL
语句转换为Linq-Entity
查询...
SELECT name, count(name) FROM people
GROUP by name
Answers:
但是请始终在控制台/日志中查找消息。如果您看到一条通知,指出您的查询无法转换为SQL,将在本地进行评估,则可能需要重写它。
Entity Framework 7(现已重命名为Entity Framework Core 1.0 / 2.0)尚不支持在生成的SQL中GroupBy()
进行转换GROUP BY
(即使在最终的1.0版本中也不会)。任何分组逻辑都将在客户端上运行,这可能会导致加载大量数据。
最终,这样编写的代码将自动开始使用GROUP BY,但是现在,如果将整个未分组的数据集加载到内存中会导致性能问题,则需要非常谨慎。
对于这是一个破坏交易的情况,您将必须手工编写SQL并通过EF执行它。
如果有疑问,请启动Sql Profiler并查看生成的内容-无论如何您都应该这样做。
https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2
一个有用的扩展是将结果收集起来Dictionary
以便快速查找(例如循环):
var resultDict = _dbContext.Projects
.Where(p => p.Status == ProjectStatus.Active)
.GroupBy(f => f.Country)
.Select(g => new { country = g.Key, count = g.Count() })
.ToDictionary(k => k.country, i => i.count);
最初在这里找到:http : //www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c
这是.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()};
转换为:
SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]
使用EF 6.2对我有用
var query = context.People
.GroupBy(p => new {p.name})
.Select(g => new { name = g.Key.name, count = g.Count() });