LINQ to Entities 不支持 LINQ 表达式节点类型“ArrayIndex"

LINQ to Entities 不支持 LINQ 表达式节点类型“ArrayIndex

问题描述:

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;
}

此代码引发以下异常:LINQ to Entities 不支持 LINQ 表达式节点类型ArrayIndex".

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

但是,如果我提供 x 而不是 aa[i] 它可以工作.

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

为什么?

要解决此问题,请使用临时变量:

To fix this use a temporary variable:

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

在你的 where 子句中有


In your where clause you have

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

这是一种表达 lambda 表达式的方式.当它转换为表达式,然后转换为对数据库的查询时,它会找到 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.