ElementAtOrDefault 的替代方案
Alternative for ElementAtOrDefault
我的业务逻辑如下。我有 CustomerEvents
table。 table 包含 CreatedAt
列和 CustomerId
列。我需要检索特定客户的上次和上次事件。关于最后我没有问题。但是以前的怎么办?我试过了ElementAtOrDefault
。但它不起作用。我会告诉你我的代码:
PrevReDepDate = context.CustomerEvents.Where(y
=> y.Customer.CustomerId == 123 && y.EventType == "deposit" && y.Again == true)
.Select(y => y.CreatedAt).OrderByDescending(y => y)
.ElementAtOrDefault(1),
没用。在我看来,这是因为 EF 无法在数据库服务器端执行它。这是异常文本:
System.InvalidOperationException: Processing of the LINQ expression 'DbSet
.ElementAtOrDefault(__p_0)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
我说的对吗?如果是,那么在 ElementAtOrDefault
?
的帮助下获取先前元素的任何替代方法
你是对的,如你所料,ElementAtOrDefault
方法无法转换为 T-SQL,Linq to Entities 无法识别它。
您可以使用 Skip
and Take
方法,如下所示:
.Select(y => y.CreatedAt).OrderByDescending(y => y).Skip(1).Take(1)
作为另一种选择,您可以使用 .ToList()
或 AsEnumerable
方法,就像这个答案 一样,但您应该知道,在加载数据后使用它们,任何进一步的操作都是使用 Linq to Objects 对内存中已有的数据执行的。因此,如果您关心性能,我不确定使用这种方法是否适合您。
我的业务逻辑如下。我有 CustomerEvents
table。 table 包含 CreatedAt
列和 CustomerId
列。我需要检索特定客户的上次和上次事件。关于最后我没有问题。但是以前的怎么办?我试过了ElementAtOrDefault
。但它不起作用。我会告诉你我的代码:
PrevReDepDate = context.CustomerEvents.Where(y
=> y.Customer.CustomerId == 123 && y.EventType == "deposit" && y.Again == true)
.Select(y => y.CreatedAt).OrderByDescending(y => y)
.ElementAtOrDefault(1),
没用。在我看来,这是因为 EF 无法在数据库服务器端执行它。这是异常文本:
System.InvalidOperationException: Processing of the LINQ expression 'DbSet .ElementAtOrDefault(__p_0)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information. at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
我说的对吗?如果是,那么在 ElementAtOrDefault
?
你是对的,如你所料,ElementAtOrDefault
方法无法转换为 T-SQL,Linq to Entities 无法识别它。
您可以使用 Skip
and Take
方法,如下所示:
.Select(y => y.CreatedAt).OrderByDescending(y => y).Skip(1).Take(1)
作为另一种选择,您可以使用 .ToList()
或 AsEnumerable
方法,就像这个答案