我宣布这样一个实体(实际的类显然也有一个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',框架将如何使用该属性并加载它?它不能“看到”它;只有儿童班才可以。 –