The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities

Artur Keyan picture Artur Keyan · Dec 2, 2011 · Viewed 35.8k times · Source
public List<string> GetpathsById(List<long> id)
{
    long[] aa = id.ToArray();
        long x;
    List<string> paths = new List<string>();
    for (int i = 0; i < id.Count; i++)
    {
        x = id[i];
        Presentation press = context.Presentations.Where(m => m.PresId == aa[i]).FirstOrDefault();
        paths.Add(press.FilePath);
    }
    return paths;
}

This code throws the following exception: The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities.

However, if I supply x instead of aa[i] it works.

Why?

Answer

George Duckett picture George Duckett · Dec 2, 2011

To fix this use a temporary variable:

var tmp = aa[i];
...
m => m.PresId == tmp

In your where clause you have

m => m.PresId == aa[i]

which is a way of expressing a lambda expression. When that is converted to an expression, then converted into a query on your database it finds the aa[i], which is an index into an array. i.e. it doesn't treat it as a constant. Since a translation of an indexer to your database language is impossible it gives the error.