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;
}
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?
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:
What do you expect the generated SQL query to be?
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:
The
.Containsmethod will be translated into aSQL INclause. This avoids sending multiple SQL queries to the database as you do in your example on each iteration.