2012-11-12 80 views
2

我遇到了一個我相信可以通過簡單的理解就可以解決的問題。我首先使用實體​​框架5,並使用POCO。我爲所有POCO對象正確配置了(虛擬)所有導航屬性。當我查詢一個對象(PO​​CO),然後返回該POCO作爲結果時,就會出現問題。爲POCO的所有導航性能null'ed:帶導航屬性返回null的EF5&分離式POCO

class PocoParent { // all of these are properties (get/set) 
    public int Id; 
    public string ParentProperty; 
    public virtual PocoChild NavProperty; 
} 
class PocoChild { 
    public int Id; 
    public int ParentId; 
    public string Name; 
    public virtual PocoParent Parent; 
} 

裏面來處理我的查詢信息庫類:

IEnumerable<PocoChildren> GetAllChildrenFor(int parentId) { 
    using(Context db = new Context()) { 
     var pcs = db.PocoParents.Where(p => p.Id == parentId); 
     return pcs; 
    } 
} 

現在使用的存儲庫:

... 
var children = repo.GetAllChildrenFor(queriedParent.Id); 
... 

現在使用的結果從存儲庫,這是錯誤發生的地方:

... 
foreach(child in children) { 
    if(child.Parent.NavProperty == "null") { !!! Exception: child.Parent ObjectContext already disposed 
    } 
} 
... 

如何處理ObjectContext(以分離POCO對象),但保留至少一個導航屬性級別?我已經無休止地尋找解決方案,但由於解決方案在如何做到這一點上彼此衝突,所以我很難過。

---回顧---- 下面給出了答案,如果我是在存儲庫中查詢更改爲以下:

IEnumerable<PocoChildren> GetAllChildrenFor(int parentId) { 
    using(Context db = new Context()) { 

     var pcs = db.PocoParents.Include(p => p.Select(prop => prop.Parent).Where(p => p.Id == parentId); 

     return pcs; 
    } 
} 

將返回所有的enities,他們將包含非空的.Parent屬性或我指定的任何屬性?

回答

2

默認情況下啓用延遲加載,這就是導航屬性爲空的原因。延遲加載意味着可導航屬性在請求之前不會被加載。如果上下文在被請求時沒有了,它們會被設置爲null,因爲它們不能被加載。

要解決此問題,您需要禁用延遲加載或顯式(並且急切地)加載所需的屬性。

MSDN magazine article是一個很好的來源,可以幫助您決定哪條路線最適合您。

+0

謝謝,我想我現在明白了。如果您不介意驗證,我會在底部重新提出我的問題以供評估。 –

+1

我一直使用Include的lambda版本運氣不好。所以我會把它寫成:... Include(「Parent」)。其中,否則,是的,我認爲你已經得到了它。 –