【发布时间】:2018-07-13 09:30:25
【问题描述】:
因此,EF Core 2.1 在 SQL 服务器上评估 GroupBy LINQ 表达式(使用 SQL 提供程序时)。
这很棒但是当查询变得更复杂时我遇到了问题。
用于这些查询的模型是:
public class Invoice
{
public string Status {get; set;}
public string InvoiceType {get; set;}
public decimal InvoicePayments {get; set;}
public decimal EligibleValue {get; set;}
}
此 LINQ 语句完全在 SQL Server 中运行:
data
.GroupBy(i => new { i.Status, i.InvoiceType })
.Select(i => new
{
i.Key,
Count = i.Count(),
Total = i.Sum(x => x.EligibleValue)
});
并生成以下SQL
SELECT
[i].[Status],
[i].[InvoiceType],
COUNT(*) AS [Count],
SUM([i].[EligibleValue]) AS [Col1]
FROM [Invoice] AS [i]
GROUP BY [i].[Status], [i].[InvoiceType]
此 LINQ 语句有效,但在内存中执行 GroupBy :
data
.GroupBy(i => new { i.Status, i.InvoiceType })
.Select(i => new
{
i.Key,
Count = i.Count(),
TotalLessThan100 = i.Where(x => x.InvoicePayments < 100).Sum(y => y.EligibleValue),
TotalLessThan500 = i.Where(x => x.InvoicePayments < 500).Sum(z => z.EligibleValue)
});
我在“输出”窗口中收到一些警告:
The LINQ expression 'GroupBy(new <>f__AnonymousType0`2(Status = [i].Status, InvoiceType = [i].InvoiceType), [i])' could not be translated and will be evaluated locally.
The LINQ expression 'Count()' could not be translated and will be evaluated locally.
The LINQ expression 'where ([x].InvoicePayments < 100)' could not be translated and will be evaluated locally.
The LINQ expression 'where ([x].InvoicePayments < 500)' could not be translated and will be evaluated locally.
The LINQ expression 'Sum()' could not be translated and will be evaluated locally.
而且生成的SQL没有GroupBy,只有初始查询。
有什么方法可以定义这个查询在 SQL Server 上完全执行?
【问题讨论】:
-
也许将
.Where()从.Select()移出 -
你知道我可以把它放在哪里吗?我需要在分组数据上评估
.Where()。我将编辑查询以显示更多完整场景 - 抱歉。 -
您可以尝试使用
.Sum(x => x.InvoicePayments < 100 ? x.EligableValue : 0)摆脱 where 子句。至少值得一试。 -
感谢@Dirk,这是一个很好的建议,但它仍然给了我很好的旧警告
The LINQ expression 'GroupBy(new <>f__AnonymousType0``2(Status = [i].Status, InvoiceType = [i].InvoiceType), [i])' could not be translated and will be evaluated locally.,然后是其他消息(尽管这次没有关于Where的警告)
标签: c# sql-server linq entity-framework-core