2010-11-20 68 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(); 
}