質問

私は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次回は()トリックを行うようだ...おかげます。

scroll top