LINQ To Entities doesn't recognize array index

后端 未结 2 1536
难免孤独
难免孤独 2021-01-25 00:02

I have following function in my code

  public List GetpathsById(List id)
        {

            List paths = new List<         


        
相关标签:
2条回答
  • 2021-01-25 00:44

    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();
    

    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:

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

    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.

    0 讨论(0)
  • 2021-01-25 01:05

    This question was asked by another user so it must be a school assignment.

    Basically I gave this same answer to the other user.

    It cannot be mapped to an SQL type or function.

    Everything you want doing in this code can be done simply using the list and iterating over it in a slightly different way.

    The following bit of code will do everything you need it to.

    public List<string> GetpathsById(List<long> id)  
    {
        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;  
    }  
    
    0 讨论(0)
提交回复
热议问题