c# - 为什么Entity Framework linq查询的内部SQL中没有GroupBy子句?
问题描述
在实体框架的文档中: https ://www.entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx
在有关 GroupBy 的部分中,我们可以阅读以下代码:
using (var ctx = new SchoolDBEntities())
{
var students = from s in ctx.Students
group s by s.StandardId into studentsByStandard
select studentsByStandard;
foreach (var groupItem in students)
{
Console.WriteLine(groupItem.Key);
foreach (var stud in groupItem)
{
Console.WriteLine(stud.StudentId);
}
}
}
按照 SQL 在内部执行:
SELECT
[Project2].[C1] AS [C1],
[Project2].[StandardId] AS [StandardId],
[Project2].[C2] AS [C2],
[Project2].[StudentID] AS [StudentID],
[Project2].[StudentName] AS [StudentName],
[Project2].[StandardId1] AS [StandardId1]
FROM ( SELECT
[Distinct1].[StandardId] AS [StandardId],
1 AS [C1],
[Extent2].[StudentID] AS [StudentID],
[Extent2].[StudentName] AS [StudentName],
[Extent2].[StandardId] AS [StandardId1],
CASE WHEN ([Extent2].[StudentID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
FROM (SELECT DISTINCT
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1] ) AS [Distinct1]
LEFT OUTER JOIN [dbo].[Student] AS [Extent2] ON ([Distinct1].[StandardId] = [Extent2]. [StandardId]) OR (([Distinct1].[StandardId] IS NULL) AND ([Extent2].[StandardId] IS NULL))
) AS [Project2]
ORDER BY [Project2].[StandardId] ASC, [Project2].[C2] ASC
go
为什么 SQL 中没有 GroupBy 子句?如果不需要 GroupBy 子句,我们不能只使用简单的 Select 和 OrderBy 而不使用 Joins 吗?谁能解释上述查询?
解决方案
底线是:因为 SQL 不能返回嵌套的结果集。
每个 SQLSELECT
语句都返回一个平面的值列表。LINQ 能够返回对象图,即具有嵌套对象的对象。这正是 LINQGroupBy
所做的。
在 SQL 中,一条GROUP BY
语句只返回分组列和聚合结果:
SELECT StandardId, COUNT(*)
FROM Students
GROUP BY StandardId;
其余的学生专栏都不见了。
LINQGroupBy
语句返回类似
StandardId
StudentId StudentName
1
21 "Student1"
15 "Student2"
2
48 "Student3"
91 "Student4"
17 "Student5"
因此,SQLGROUP BY
语句永远不能成为 LINQ 的来源GroupBy
。
Entity Framework (6) 知道这一点,它会生成一条 SQL 语句,从数据库中提取所有需要的数据,添加一些使分组更容易的部分,并在客户端创建分组。
推荐阅读
- javascript - 如何将 puppeteer Array.from().map() 从 C# 转换为 JavaScript
- java - 在 android 客户端中使用 GRPC 创建 2 次 ssl 握手 (TLS)
- wordpress - 在特定管理员 URL 上禁用 Wordpress 插件
- c# - 为什么 Aspnet.Core 模型验证不对 Nullable 属性抛出异常?
- php - array_multisort $FILES 数组
- c - 将解决方案重定向到最新 SDK (10.0.18362) 后 WINNT.H 中的编译器错误
- c# - 在 IConfigureOptions 中获取 DatabaseContext 实例
- php - 如何在php中爆炸csv数组?
- mongodb - 使用 mongodb(spring boot) 执行搜索/查找操作时如何重命名字段?
- decorator - 在 nestjs 参数装饰器中禁用验证