2017-04-14 61 views
3

假設我們有一個像下面的第三Dbsets:的EntityFramework包括(貪婪加載)虛擬財產的虛擬財產

Category 
{ 
... 
    public virtual ICollection<Item> Items {get; set;} 
... 
} 

Item 
{ 
... 
    public virtual ICollection<Specification> Specifications{get; set;} 
... 
} 

Specification 
{ 
... 
} 

對於預先加載我用這樣的:

Category cat = db.Categories.Include(c=> c.Items).FirstOrDefault(c=> c.Id == 1); 

但現在的問題是

cat.Items[0].Specificationsnull,我們怎樣才能使它成爲熱門的集合子集合呢?

P.S .:我試圖刪除virtual關鍵字進行測試(我不想刪除它),但它也沒有工作。

+0

如果*轉到VS定義爲*'Include'方法,你會發現一個完整的幫助主題,描述不同的'Include'場景。基本上你需要使用「選擇」向下導航。 –

+0

您可以使用其他包含。以字符串作爲參數的那個。然後你可以這樣做:'Include(「Items.Specifications」)' – Alex

回答

5

您也可以使用符號

db.Categories.Include("Items.Specifications") 

說明它已經是一個字符串

+1

如果您重命名「Items」或「Specifications」屬性,Visual Studio將不會重構此字符串。 –

+0

@MariusOrha這是另一個問題。事實是馬克的解決方案將工作 – Alex

+0

這只是一個額外的信息。 –

6
Category cat = db.Categories 
     .Include(c => c.Items.Select(s => s.Specifications)) 
     .FirstOrDefault(c => c.Id == 1); 
+0

只是想明確說明虛擬與問題無關。 –

+0

是的,選擇部分是有義務的。 –