我遇到了一個我相信可以通過簡單的理解就可以解決的問題。我首先使用實體框架5,並使用POCO。我爲所有POCO對象正確配置了(虛擬)所有導航屬性。當我查詢一個對象(POCO),然後返回該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屬性或我指定的任何屬性?
謝謝,我想我現在明白了。如果您不介意驗證,我會在底部重新提出我的問題以供評估。 –
我一直使用Include的lambda版本運氣不好。所以我會把它寫成:... Include(「Parent」)。其中,否則,是的,我認爲你已經得到了它。 –