LINQ到实体无​​法识别数组索引 [英] LINQ To Entities doesn't recognize array index

查看:105
本文介绍了LINQ到实体无​​法识别数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在code下面的函数

I have following function in my code

  public List<string> GetpathsById(List<long> id)
        {

            List<string> paths = new List<string>();
            for (int i = 0; i < id.Count; i++)
            {

                Presentation press = context.Presentations.Where(m => m.PresId == id[i]).FirstOrDefault();
                paths.Add(press.FilePath);
            }
            return paths;
        }

但是当我尝试这一点,compiller得到错误是这样的。

But when I try this, compiller get error like this.

LINQ to Entities does not recognize the method 'Int64 get_Item(Int32)' method, and this method cannot be translated into a store expression.

然后我尝试做这样的事情和一切工作正常。

Then I try to do something like this and all works fine.

  public List<string> GetpathsById(List<long> id)
        {
             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 == x).FirstOrDefault();
                paths.Add(press.FilePath);
            }
            return paths;
        }

所以我想知道,为什么呢?我不能让在我的脑海里行为的任何答复。任何人能解释这个悖论?

So I wonder, why? I can't get any answer for that behaviour in my mind. Can anyone explain this paradox?

推荐答案

有什么神奇的:前pression树被转换成SQL查询,这就是关系数据库理解。你可以做在离pression树几乎所有的东西。遗憾的是并不是所有的操作都​​执行。请看下面的例子:

There's no magic: expression trees are translated into SQL queries which is what relational databases understand. You could do almost anything in an expression tree. Unfortunately not all operations are implemented. Consider the following example:

Presentation press = context
   .Presentations
   .Where(m => SomeCustomFunctionThatUsesUnmanagedPInvokeCode(m.PresId))
   .FirstOrDefault();

你有什么期望生成的SQL查询来呢?

What do you expect the generated SQL query to be?

这是与数组索引的情况。它们不能转换成SQL查询。

That's the case with array indexers. They cannot be translated into SQL queries.

这是说,你的情况,下面可能有点简单:

This being said, in your case, the following might be a little simpler:

public List<string> GetpathsById(List<long> id)
{
    return
        (from p in context.Presentations
         where id.Contains(p.PresId)
         select p.FilePath
        ).ToList();
}

。载方法将被翻译成 SQL IN 条款。这就避免了发送多个SQL数据库查询,你在你的例子做每一次迭代。

The .Contains method will be translated into a SQL IN clause. This avoids sending multiple SQL queries to the database as you do in your example on each iteration.

这篇关于LINQ到实体无​​法识别数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆