2011-12-02 30 views
1

在我的代碼LINQ到實體不承認我有以下功能數組索引

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得到錯誤這樣的。

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

然後我嘗試做這樣的事情,一切正常。

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

所以我想知道爲什麼?在我的腦海裏,我無法得到任何答案。任何人都可以解釋這個矛盾嗎?

回答

2

沒有什麼神奇的:表達式樹被轉換成SQL查詢,這是關係數據庫理解的。你可以在表達式樹中做幾乎任何事情。不幸的是,並不是所有的操作都實施了考慮下面的例子:

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

你期望生成的SQL查詢是什麼?

這就是數組索引器的情況。他們不能被翻譯成SQL查詢。

這是說,你的情況,下面可能是稍微簡單一些:

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

.Contains方法將被翻譯成SQL IN條款。這樣可以避免將多個SQL查詢發送到數據庫,就像在每次迭代中的示例中一樣。

+0

我也這麼認爲...... –

+0

謝謝......但是他不能簡單地將該索引的值翻譯成SQL嗎? –

+0

令人驚歎...爲什麼'包含'正在工作? –

1

這個問題被另一個用戶提問,因此它必須是一個學校作業。

基本上我給這個相同的答案給其他用戶。

它無法映射到SQL類型或函數。

你想在這段代碼中做的任何事情都可以簡單地使用列表來完成,並以稍微不同的方式迭代它。

以下幾段代碼將完成您需要的一切。

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

這是同樣的答案,在這個主題? http://stackoverflow.com/questions/8353948/the-linq-expression-node-type-arrayindex-is-not-supported-in-linq-to-entities –

+0

是的,你們都有非常相似的代碼和類似的題。 –