Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么实体框架linq查询的内部SQL中没有GroupBy子句?_C#_Sql_Entity Framework_Group By_Entity Framework 6 - Fatal编程技术网

C# 为什么实体框架linq查询的内部SQL中没有GroupBy子句?

C# 为什么实体框架linq查询的内部SQL中没有GroupBy子句?,c#,sql,entity-framework,group-by,entity-framework-6,C#,Sql,Entity Framework,Group By,Entity Framework 6,在实体框架的文档中: 在关于GroupBy的部分中,我们可以阅读以下代码: using (var ctx = new SchoolDBEntities()) { var students = from s in ctx.Students group s by s.StandardId into studentsByStandard select studentsByStandard; foreach (

在实体框架的文档中:

在关于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子句,我们就不能使用带OrderBy和不带连接的simpleselect吗?有人能解释一下上面的查询吗?

底线是:因为SQL不能返回嵌套的结果集

每个SQL
SELECT
语句都返回一个简单的值列表。LINQ能够返回对象图,即具有嵌套对象的对象。这正是LINQ的
GroupBy
所做的

在SQL中,
GROUPBY
语句只返回分组列和聚合结果:

选择标准ID,计数(*)
来自学生
按标准ID分组;
剩下的学生专栏都不见了

LINQ
GroupBy
语句返回如下内容

standarid
StudentId StudentName
1.
21“学生1”
15“学生2”
2.
48“学生3”
91“学生4”
17“学生5”
因此,SQL
GroupBy
语句永远不能作为LINQ
GroupBy
的源


实体框架(6)知道这一点,它生成一个SQL语句,从数据库中提取所有必需的数据,添加一些使分组更容易的部分,并在客户端创建分组。

但是为什么我们不能在没有连接和OrderBy的情况下进行简单的选择呢?因为“我们”什么都不做:)。EF决定创建这种查询,我认为是因为它保证了可以在客户端创建组。