2010-11-20 67 views
0

我有一個C#-4 MVC3 RC測試應用程序,它使用實體框架4.EF4 LINQ的返回類型泛型列表

我有這樣的方法:

public static List<Content> FetchMenu(int websiteID) { 
    return (from w in ContextHelper.Current.Websites 
      where w.WebsiteID == websiteID 
      select w.Contents).ToList(); 
} 

這裏涉及的對象(內容和網站)是EntityObject類型的。

上述函數給出編譯錯誤:

Cannot implicitly convert type 'System.Linq.IQueryable<System.Collections.Generic.List<Manager.Models.Content>>' to 'System.Collections.Generic.List<Manager.Models.Content>'. An explicit conversion exists (are you missing a cast?) 

w.Contents是EntityCollection<Content>類型的集合。

如何推遲Linq.IQueryable類型以返回類型爲Content的泛型列表?

回答

2

您需要使用括號,讓你申請ToList()整個查詢(IQueryable類型的對象):

public static List<Content> FetchMenu(int websiteID) { 
    return (from w in ContextHelper.Current.Websites 
      where w.WebsiteID == websiteID 
      select w.Contents).ToList(); 
} 

否則你正在呼籲只有w.ContentsToList()select是繼應用。如果我顯示方法鏈接語法,可能會更清楚。

您的版本:

ContextHelper. 
      Current. 
      Websites. 
      Where(w => w.WebsiteID == websiteID). 
      Select(w => w.Contents.ToList()); 

正確的版本:

ContextHelper. 
      Current. 
      Websites. 
      Where(w => w.WebsiteID == websiteID). 
      Select(w => w.Contents). 
      ToList(); 

編輯

由於w.Contents是一個集合,則需要使用SelectMany來壓平:

public static List<Content> FetchMenu(int websiteID) { 
    return ContextHelper. 
      Current. 
      Websites. 
      Where(w => w.WebsiteID == websiteID). 
      SelectMany(w => w.Contents). 
      ToList(); 
} 
+0

我確實忘了括號,但它仍然給另一轉換錯誤:爲了完整起見,這裏使用「查詢綜合」語法無法隱式轉換類型「System.Collections.Generic.List >'改爲'System.Collections.Generic.List ' – peter 2010-11-20 23:00:47

0

The.First()似乎在做伎倆......謝謝。

+1

通過首先使用,您將只從每個「Contents」集合中選擇一個項目爲每個網站)。要獲取所有項目,請使用'SelectMany'。看到我更新的帖子。 – Yakimych 2010-11-20 23:16:33

+0

這就是我的想法,但.First()也會選擇所有項目。我認爲這意味着它會選擇第一個包含所有內容項的集合。 – peter 2010-11-21 00:19:09

0

Yakimych's answer使用SelectMany()是相關的。

public static List<Content> FetchMenu(int websiteID) { 
    return (from w in ContextHelper.Current.Websites 
      where w.WebsiteID == websiteID 
      from c in w.Contents 
      select c).ToList(); 
}