在Orderby中使用Max() [英] using Max() in Orderby
问题描述
我有这条线,直到我启用RelationalEventId.QueryClientEvaluationWarning为止。
I have this line which runs till I enabled RelationalEventId.QueryClientEvaluationWarning.
在这里,我要说的是根据客户的最新订购日期对结果(客户)进行排序。
Here let's say what I want to do is to sort the results (customers) based on their latest order date.
.OrderByDescending(x=>x.orders.Max(y=>y.CreateDate))
按如下方式配置上下文后,我意识到Max()不会转换为TSql。
After I configure the context as follow I realised the Max() is not converted to 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上的最大值?
I assume calculating the max locally is against having a better performance. Is there any way to calculate the max on SQL Server?
推荐答案
在以下情况下调用聚合方法(平均,最小,最大)时:
When you call aggregate methods (Average, Min, Max) in a LINQ query using a non-nullable type, it has no choice but to evaluate it locally.
为避免这种情况,请将您的Max值强制转换为可为空的类型,它将在本地对它进行评估。在数据库中进行评估。
To avoid this, cast your Max value to a nullable type and it will be evaluated in the database.
假定CreateDate的类型为DateTime,并将其转换为DateTime吗? (可为空)应该起作用。
Assuming CreateDate is of type DateTime, casting it to DateTime? (nullable) should work.
这是您的查询的样子:
.OrderByDescending(x=>x.orders.Max(y=> (DateTime?)y.CreateDate))
这篇关于在Orderby中使用Max()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!