我正在使用Entity Framework Core 2.2.6对Sql Server数据库运行一个简单查询,但是GroupBy不在服务器上执行,而是在本地执行。
我是否缺少某些东西,这些东西会迫使该小组进入服务器?
我尝试过的EF查询的2个变化形式:
public class Holiday
{
public int Id {get;set;}
public DateTime Date {get;set;}
public string Username {get;set;}
public string Approver {get;set;}
}
//version 1
await _dbContext.Holidays
.GroupBy(h => new { h.Date})
.ToDictionaryAsync(x => x.Key.Date, x => x.Select(x1 => x1.Username).ToList());
//version 2
await _dbContext.Holidays
.GroupBy(h => h.Date)
.ToDictionaryAsync(x => x.Key, x => x.Select(x1 => x1.Username).ToList());
两个版本都会产生以下SQL:
SELECT [h].[Id], [h].[Approver], [h].[Date], [h].[HolidayTypeId], [h].[OwningRequestId], [h].[HolidayStatusId], [h].[Username]
FROM [Holidays] AS [h]
ORDER BY [h].[Date]
产生警告:
警告:Microsoft.EntityFrameworkCore.Query [20500] LINQ表达式'GroupBy([h] .Date,[h])'无法翻译,将在本地进行评估。
评论建议
//group by string
await _dbContext.Holidays
.GroupBy(h => h.Username)
.ToDictionaryAsync(x => x.Key, x => x.Select(x1 => x1.Username).ToList());
//group by part of date
await _dbContext.Holidays
.GroupBy(h => h.Date.Year)
.ToDictionaryAsync(x => x.Key, x => x.Select(x1 => x1.Username).ToList());
--group by string
SELECT [h].[Id], [h].[Approver], [h].[Date], [h].[HolidayTypeId], [h].[OwningRequestId], [h].[HolidayStatusId], [h].[Username]
FROM [Holidays] AS [h]
ORDER BY [h].[Username]
--group by part of date
SELECT [h].[Id], [h].[Approver], [h].[Date], [h].[HolidayTypeId], [h].[OwningRequestId], [h].[HolidayStatusId], [h].[Username]
FROM [Holidays] AS [h]
ORDER BY DATEPART(year, [h].[Date])
答案 0 :(得分:5)
这是因为没有这样的SQL查询。
像SQL。如果要按日期组获取用户名,则两者都需要。
基本上:
await _dbContext.Holidays
.GroupBy(h => new { h.Date, h.Username})
.Select(g => new
{
g.Key.Date,
g.Key.Username
});
这将产生这样的SQL查询。
SELECT [h].[Date],[h].[Username]
FROM [Holidays] AS [h]
GROUP BY [h].[Date],[h].[Username]
之后,您可以根据需要使用数据创建字典的结构。
答案 1 :(得分:2)
问题是,当您尝试在数据库中进行分组时,实际上并没有实现组内值的方法。您只会进入<security>
<requestFiltering>
<fileExtensions>
<add fileExtension=".ttf" allowed="true" />
</fileExtensions>
</requestFiltering>
</security>
个分组列或非分组列的汇总值(通过SELECT
等)。
例如:
SUM
此查询将生成结果集,其中每行将有两列,即日期和名称。
尽管如此,我们还是尝试分组:
SELECT [h].[Date], [h].[Username]
FROM [Holidays] AS [h]
此SQL查询根本不会被评估,因为从SQL Server角度来看它是无效的。错误消息将是
SELECT [h].[Date], [h].[Username]
FROM [Holidays] AS [h]
GROUP BY [h.Date]
总结所有这些,您可以按照@Ercan Tirman的建议进行操作,或者加载所有用户名和日期并在内存中进行分组:
Column 'Holidays.Username' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.