我宣佈這樣一個實體(實際的類顯然也有一個ID屬性,映射完成等,但它不是問題,所以我在這裏省略吧):不實體框架是否支持受保護的導航屬性?
public class Parent
{
public virtual ICollection<Child> Children {get; set;}
}
該作品完美:
public class Consumer
{
void DoBusiness()
{
using (var ctx = new MyDbContext())
{
var entity = ctx.Parents.Find(keyOfParent);
// This is as expected: entity.Children refers to a collection which
// Entity Framework has assigned, a collection which supports lazy loading.
}
}
}
現在我改變了孩子們收集的知名度,被保護:
public class Parent
{
protected virtual ICollection<Child> Children {get; set;}
}
這帶來了一個意想不到的結果:
public class Consumer
{
void DoBusiness()
{
using (var ctx = new MyDbContext())
{
var entity = ctx.Parents.Find(keyOfParent);
// This is NOT as expected: entity.Children is null. I would expect, that it
// had been referring to a collection which Entity Framework would have been
// assigning, a collection which should support lazy loading.
}
}
}
此外,如果我的情況,那裏的兒童保護嘗試通過顯式地加載孩子:
ctc.Entry(entity).Collection(x => x.Children)
然後我得到這個異常:
屬性「 「父母」類型的「孩子」不是導航屬性。引用和收集方法只能與導航屬性一起使用。使用Property或ComplexProperty方法。
因此:爲了擁有使用實體框架的受保護導航屬性,我應該做些什麼?
爲什麼你想在地球上做到這一點? EF中的「實體」不過是數據庫表,記錄和關係的對象表示。他們不應該包含業務邏輯。因此,他們和他們的成員應該是可見的,以便用於查詢。示例代碼'ctc.Entry(entity).Collection(x => x.Children)'只能在與這些原則相違背的Parent類中運行。 –
由於具體屬性(與示例中的Children相對應)僅通過反射來使用,因此您提供的有關查詢的基本考慮事項不適用。關於你的編碼評論:顯然,是的,但它強調實體框架在被保護之後不會將該屬性視爲導航屬性。你也有一些貢獻信息嗎? –
如果該屬性標記爲'protected',框架將如何使用該屬性並加載它?它不能「看到」它;只有兒童班纔可以。 –