EF4 LINQ的返回类型泛型列表
-
26-09-2019 - |
题
我有一个C#-4其使用实体框架4 MVC3 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.Contents是EntityCollection<Content>
类型的集合。
我如何推迟Linq.IQueryable类型返回类型内容的通用列表?
解决方案
您需要使用括号,让您应用ToList()
整个查询(类型IQueryable
的对象):
public static List<Content> FetchMenu(int websiteID) {
return (from w in ContextHelper.Current.Websites
where w.WebsiteID == websiteID
select w.Contents).ToList();
}
否则,你就只能ToList()
调用w.Contents
和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();
}
其他提示
var query = (from w in ContextHelper.Current.Websites
where w.WebsiteID == websiteID
select w.Contents).First();
return query.ToList();
在。首先()似乎做的伎俩...谢谢。
Yakimych的使用SelectMany()
答案是corret。为了完整起见,在这里它是使用“询问理解”语法:
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();
}
不隶属于 StackOverflow