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.
Here is the stack trace:
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)
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).
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?
It would be nice to avoid runtime exceptions.
LINQ does not support full outer joins directly, the same as right outer joins.
You can write LINQ queries in C# for SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. LINQ support is also provided by third parties for many Web services and other database implementations.
Most of the LINQ projection and restriction methods are supported in LINQ to Entities queries, with the exception of those that accept a positional argument. For more information, see Standard Query Operators in LINQ to Entities Queries.
The ElementAt operator is used to return an element from the particular index from the given collection or sequence.
From MSDN, Standard Query Operator Translation (LINQ to SQL) - this article contains the full list of operators that haven't been translated:
Operators with No Translation
The following methods are not translated by LINQ to SQL. The most common reason is the difference between unordered multisets and sequences.
Operators
Rationale
...
ElementAt , ElementAtOrDefault
SQL queries operate on multisets, not on indexable sequences.
It is odd, in particular because Skip()
is supported. Could you, for example, do:
var obj = source.Skip(index).First();
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With