LINQ 表达式节点类型“ArrayIndex”在 LINQ to Entities 中不受支持

本文关键字:LINQ Entities 支持 to 节点 表达式 类型 ArrayIndex | 更新日期: 2023-09-27 18:16:20

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

此代码引发以下异常:The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities.

但是,如果我提供x而不是aa[i]它就可以了。

为什么?

LINQ 表达式节点类型“ArrayIndex”在 LINQ to Entities 中不受支持

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

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

在你的 where 子句中,你有

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

这是一种表达 lambda 表达式的方式。当它被转换为表达式,然后转换为数据库上的查询时,它会找到aa[i],这是数组的索引。即它不将其视为常量。由于不可能将索引器转换为数据库语言,因此会出现错误。

显然,如果您在表达式树中使用array index (aa[i]),它也会尝试将其转换为表达式。

只需使用单独的变量来解决它:

int presId = aa[i];
Presentation press = context.Presentations.Where(m => m.PresId == presId).FirstOrDefault();
 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];
    int temp = aa[i];
    Presentation press = context.Presentations.Where(m => m.PresId == temp).FirstOrDefault();
    paths.Add(press.FilePath);
}
return paths;
}

试试这个

它不能映射到 SQL 类型或函数。

您知道您正在将列表和数组相互混合。您想在此代码中执行的所有操作都可以简单地使用列表来完成。

以下代码将完成您需要的所有操作。

public List<string> GetpathsById(List<long> id) 
{ 
        long x; 
    List<string> paths = new List<string>(); 
    foreach(long aa in id) 
    { 
        Presentation press = context.Presentations.Where(m => m.PresId == aa).FirstOrDefault(); 
        paths.Add(press.FilePath); 
    } 
    return paths; 
} 
public List<string> GetpathsById(List<long> id) 
{ 
        long x; 
    List<string> paths = new List<string>(); 
    foreach(long aa in id) 
    { 
        Presentation press = context.Presentations.Where(m => m.PresId == aa).FirstOrDefault(); 
        paths.Add(press.FilePath); 
    } 
    return paths; 
} 

public IEnumerable<String> GetpathsById(List<long> id) 
{ 
    foreach(long item in id) 
        yield return = (context.Presentations.Where(m => m.PresId == item).FirstOrDefault()).FilePath
} 

"短风格",但如果写了很多其他函数,不建议使用。

可以简化以避免错误:

public List<string> GetpathsById(List<long> id)
{
    return context.Presentations.Where(x => id.Contains(x.PresId)).Select(x => x.FilePath).ToList();
}