Sunday, October 2, 2011

The query operator 'ElementAt' is not supported.

Scenario:
I have products list sorted according to their work priority and now I want to fetch
the next product  to number of processed products as:
int noOfProducts = context.ProcessedProducts.Count(product => product.ClientId.Equals(clientID));
    if (noOfProducts > 0)

    {

      nextProductID = context.Products.OrderBy(prd => prd.Priority).Where(prod => 
                               prod
.Equals(clientID)).ElementAt(noOfProducts +1).Id; //error

    }

Here I got an exception of
NotSupportedException: The query operator 'ElementAt' is not supported.

Reason:
The exception is telling you what you need to know.  LINQ to SQL cannot translate
ElementAt into SQL.  It does not support translating any of the query operators that
have an index argument.

Solutions:
Instead you can used the First, FirstOrDefault, Single or SingleOrDefault operators. 

int x = resultToAdd.First().ID;

or
use skip and take statement to improve processing

query.Skip(2).Take(1).Single();

or
This solution is little inefficient, because the whole query is executed and converted
to a List.
query.Take(2).ToList().ElementAt(1);

and I have I implemented my solution as:
nextProductID = context.Products.OrderBy(prd => prd.Priority).Where(prod => 
                               prod.Equals(clientID)).Skip(noOfProducts).Take(1).Single().Id;

 

No comments :

Post a Comment