为什么 LINQ to SQL 不支持查询运算符“ElementAt"? [英] Why is the query operator 'ElementAt' is not supported in LINQ to SQL?

查看:21
本文介绍了为什么 LINQ to SQL 不支持查询运算符“ElementAt"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 LINQ to SQL 中,当我尝试在从 LINQ to SQL 查询返回的 IQueryable 上使用 ElementAt 扩展方法时,出现异常不支持查询运算符 'ElementAt'.".

In LINQ to SQL, I get the exception "The query operator 'ElementAt' is not supported." When trying to use the ElementAt extension method on an IQueryable returned from a LINQ to SQL query.

这是堆栈跟踪:

at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
   at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)
   at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
   at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
   at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.ElementAt[TSource](IQueryable`1 source, Int32 index)

现在我意识到要摆脱这个异常并使用 ElementAt 我可以在使用扩展方法之前调用 '.ToList()' 并且它会起作用.这很好,但我仍然不喜欢这是一个运行时异常(以及似乎违反 LSP 的情况).

Now I realize to get rid of this exception and to use ElementAt I could call '.ToList()' before using the extension method and it will work. That is fine, but I still don't like the fact that this is a runtime exception (and what seems like LSP violation).

有什么原因不能支持这些方法吗?仅仅是因为它们无法轻松转换为 SQL 吗?不支持其他哪些 IQueryable/IEnumerable 扩展方法,是否有列表?

Is there a reason why these methods cannot be supported? Is it just because they cannot be translated easily into SQL? What other IQueryable/IEnumerable extension methods are not supported, is there a list somewhere?

最好避免运行时异常.

推荐答案

来自 MSDN,标准查询运算符翻译(LINQ to SQL) - 本文包含尚未翻译的运算符的完整列表:

From MSDN, Standard Query Operator Translation (LINQ to SQL) - this article contains the full list of operators that haven't been translated:

  • TakeWhile ,SkipWhile
  • 反向
  • 最后一个,最后一个或默认值
  • ElementAt , ElementAtOrDefault
  • DefaultIfEmpty

无需翻译的运算符

以下方法不由 LINQ 翻译成 SQL.最多共同的原因是差异在无序多重集和序列.

The following methods are not translated by LINQ to SQL. The most common reason is the difference between unordered multisets and sequences.

运算符

基本原理

...

ElementAt ,ElementAtOrDefault

ElementAt , ElementAtOrDefault

SQL 查询对多集进行操作,而不是关于可索引序列.

SQL queries operate on multisets, not on indexable sequences.

这篇关于为什么 LINQ to SQL 不支持查询运算符“ElementAt"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆