gpt4 book ai didi

linq - 带有查询的 Entity Framework 错误?

转载 作者:行者123 更新时间:2023-12-04 05:08:11 24 4
gpt4 key购买 nike

我有一个包含这些数据的数组( IDTimeName ):

var array = new[]
{
new { ID = 1, Time = DateTime.ParseExact("12:01", "HH:mm", null), Name = "Peter" },
new { ID = 2, Time = DateTime.ParseExact("12:06", "HH:mm", null), Name = "James" },
new { ID = 3, Time = DateTime.ParseExact("12:03", "HH:mm", null), Name = "Jackie" },
new { ID = 4, Time = DateTime.ParseExact("12:08", "HH:mm", null), Name = "Peter" },
new { ID = 5, Time = DateTime.ParseExact("12:05", "HH:mm", null), Name = "James" },
new { ID = 6, Time = DateTime.ParseExact("12:07", "HH:mm", null), Name = "Peter" },
};

数组上的以下语句会产生正确的结果:
var result = array.OrderBy(x => x.Time).GroupBy(x => x.Name)
.SelectMany(x => x).ToArray();

结果:
Time: 2013/3/6 12:01:00, Name: Peter
Time: 2013/3/6 12:07:00, Name: Peter
Time: 2013/3/6 12:08:00, Name: Peter
Time: 2013/3/6 12:03:00, Name: Jackie
Time: 2013/3/6 12:05:00, Name: James
Time: 2013/3/6 12:06:00, Name: James

但是当我在EF和SQL Server中使用相同的语句时,顺序是错误的:
Time: 2013/3/6 12:03:00, Name: Jackie
Time: 2013/3/6 12:06:00, Name: James
Time: 2013/3/6 12:05:00, Name: James
Time: 2013/3/6 12:07:00, Name: Peter
Time: 2013/3/6 12:01:00, Name: Peter
Time: 2013/3/6 12:08:00, Name: Peter

这是 SQL EF 生成的:
SELECT 
[Extent2].[Id] AS [Id],
[Extent2].[Time] AS [Time],
[Extent2].[Name] AS [Name]
FROM (SELECT DISTINCT
[Extent1].[Name] AS [Name]
FROM [dbo].[testt1] AS [Extent1] ) AS [Distinct1]
INNER JOIN [dbo].[testt1] AS [Extent2]
ON ([Distinct1].[Name] = [Extent2].[Name]) OR
(([Distinct1].[Name] IS NULL) AND ([Extent2].[Name] IS NULL))

没有 order by条款。
  • 我忘记了什么?这是EF的错误吗?
  • 如何从 EF 获得与从数组相同的结果?
  • 最佳答案

    就像在 SQL 中一样:

    先分组,再下单:

    var result = array.GroupBy(x => x.Name)
    .Select(x => x.OrderBy(y => y.Time))
    .SelectMany(x => x)
    .ToArray();

    但在你的情况下,我不明白你为什么需要这个小组。每次似乎都不同,因此产生相同结果(至少对于您的测试数据)的更简单版本将是:
    var result = array.OrderBy(x => x.Name)
    .ThenBy(y => y.Time)
    .ToArray();

    关于linq - 带有查询的 Entity Framework 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15241072/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com