2013-02-22 61 views
9

我想用LINQ查詢選擇從我的數據庫表2組的元素,我看到它使用UNION我沒有太多的經驗,一個例子,但我想,也許這正是我需要的,但我得到一個我無法修復的錯誤,我不確定它是否可以修復。因此,這裏是我的查詢:的Linq UNION查詢選擇兩個元素

IList<String> materialTypes = ((from tom in context.MaterialTypes 
            where tom.IsActive == true 
            select tom.Name) 
            .Union(from tom in context.MaterialTypes 
            where tom.IsActive == true 
            select (tom.ID))).ToList(); 

其中,因爲它似乎在抱怨試圖在IQueryable使用UNIONIEnumarebale。我試圖通過添加ToString()這樣來解決這個問題 - (tom.ID).ToString導致清潔錯誤下劃線在Visual-Studio-2010但在運行時,我得到:

{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."} 

泰,Leron。

+4

你爲什麼不選擇'new {tom.Name,tom.ID}'而不是'Union'? – 2013-02-22 10:49:29

+0

我想使用數據作爲我的'DataSource',如果我嘗試使用它會給出一個錯誤,無法從匿名類型轉換爲字符串。如果在'.ToList()'之前添加'ToString()',我會得到另一個轉換錯誤 - 這次從'char'到'String','Union'是我在這種情況下看到的解決方案。有另一種方法嗎? – Leron 2013-02-22 10:54:48

回答

25

編輯:

好吧,我發現爲什麼在LINQtoEF的int.ToString()失敗,請閱讀這篇文章: Problem with converting int to string in Linq to entities

這工作在我身邊:

 List<string> materialTypes = (from u in result.Users 
             select u.LastName) 
         .Union(from u in result.Users 
           select SqlFunctions.StringConvert((double) u.UserId)).ToList(); 

在你的它應該是這樣的:

IList<String> materialTypes = ((from tom in context.MaterialTypes 
             where tom.IsActive == true 
             select tom.Name) 
             .Union(from tom in context.MaterialTypes 
             where tom.IsActive == true 
             select SqlFunctions.StringConvert((double)tom.ID))).ToList(); 

謝謝,我今天學到了東西:)

+0

再次 - 「LINQ to Entities無法識別方法'System.String ToString()'方法,並且此方法不能轉換爲商店表達式。」來自我原始文章的錯誤是一個內部異常。這是我嘗試你的方式時得到的。我認爲與括號相同。 – Leron 2013-02-22 11:00:53

+0

大聲笑,我會去吃午飯,然後測試它。如果它的工作會接受你的回答 – Leron 2013-02-22 11:10:04

+0

更改我的帖子,所以我認爲它更清晰:) – Tom 2013-02-22 11:40:01