gpt4 book ai didi

c# - 在 Orderby 中使用 Max()

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:52 26 4
gpt4 key购买 nike

我有这条线一直运行到我启用 RelationalEventId.QueryClientEvaluationWarning。

这里假设我想要做的是根据他们的最新订单日期对结果(客户)进行排序。

.OrderByDescending(x=>x.orders.Max(y=>y.CreateDate))

按如下方式配置上下文后,我意识到 Max() 未转换为 TSql。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.ConfigureWarnings(warning =>
{
warning.Throw(RelationalEventId.QueryClientEvaluationWarning);
});
}

错误:

InvalidOperationException: Error generated for warning 'Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning: The LINQ expression 'Max()' could not be translated and will be evaluated locally.

我假设在本地计算最大值不利于获得更好的性能。有什么方法可以计算 SQL Server 上的最大值吗?

最佳答案

如果你有 EF Core Logging启用,您会看到以下警告:

=> Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor

Possible unintended use of a potentially throwing aggregate method (Min, Max, Average) in a subquery. Client evaluation will be used and operator will throw if no data exists. Changing the subquery result type to a nullable type will allow full translation.

基本上,他们试图在 LINQ to Objects 中保留上述聚合方法的抛出行为。

解决方案在最后一句话中。例如如果 CreateDate 的类型是 DateTime,那么

.OrderByDescending(x => x.orders.Max(y => (DateTime?)y.CreateDate))

将被翻译成 SQL。

关于c# - 在 Orderby 中使用 Max(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54753362/

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