EF4 LINQの戻り値の型の一般的なリスト
-
26-09-2019 - |
質問
私はEntity Frameworkの4を使用しているC#-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();
1次回は()トリックを行うようだ...おかげます。
SelectMany()
を使用する Yakimychの答えは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