Collections EF4 Linq返回类型泛型列表

Collections EF4 Linq返回类型泛型列表,collections,entity-framework-4,asp.net-mvc-3,Collections,Entity Framework 4,Asp.net Mvc 3,我有一个使用EntityFramework4的C-4MVC3 RC测试应用程序 我有这个方法: public static List<Content> FetchMenu(int websiteID) { return (from w in ContextHelper.Current.Websites where w.WebsiteID == websiteID select w.Contents).ToList(); } 内

我有一个使用EntityFramework4的C-4MVC3 RC测试应用程序

我有这个方法:

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、 内容是EntityCollection类型的集合


如何延迟Linq.IQueryable类型以返回类型内容的通用列表?

您需要使用括号,以便将列表应用于IQueryable类型的整个查询:

正确版本:

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

由于w.Contents是一个集合,您需要使用SelectMany将其展平:

第一个似乎起了作用。。。谢谢。

使用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();
}

我确实忘记了括号,但它仍然给出了另一个转换错误:无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”。通过使用first,您将只能从每个网站的每个内容集合中选择一项。要获取所有项目,请使用SelectMany。看我更新的帖子。我也是这么想的,但是。首先还要选择所有项目。我认为这意味着它将选择第一个集合,其中包含所有内容项。
ContextHelper.
           Current.
           Websites.
           Where(w => w.WebsiteID == websiteID).
           Select(w => w.Contents).
           ToList();
public static List<Content> FetchMenu(int websiteID) {
    return ContextHelper.
           Current.
           Websites.
           Where(w => w.WebsiteID == websiteID).
           SelectMany(w => w.Contents).
           ToList();
}
    var query = (from w in ContextHelper.Current.Websites
                 where w.WebsiteID == websiteID
                 select w.Contents).First();

    return query.ToList();
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();
}