为什么RelationshipManager.GetRelatedReference(,)总是返回EntityReference?具有空值?
由于某种原因,导航属性不适用于我的实体框架模型。
从 N->1 方向
,每次我尝试获取 EntityReference 时,它都会带有 null 值,即使 EntityKey 是正确的。
从方向1->N
,集合始终为空。
这种行为在我的整个模型中是一致的。
无论原因是什么,我认为它应该引发异常,而不是默默地检索不一致的引用。
引用带有空值的可能原因是什么?
编辑
我刚刚注意到它与延迟加载有关。 EntityReference(T) 的 IsLoaded 属性设置为 false,并且显式调用 Load 方法可以解决该问题。问题在于访问导航属性时调用的方法 RelationshipManager.GetRelatedReference
应加载 EntityReference。不应该吗?
For some reason, navigation properties are not working on my Entity Framework model.
From the direction N->1
, every time I attempt to obtain a EntityReference it comes with null value, even though the EntityKey is correct.
From the direction 1->N
, the collection is always empty.
This behavior is consistent throughout my entire model.
Whatever the reason is, I think it should raise an exception intead of silently retrieving an inconsistent reference.
What are the possible reasons a reference would come with null value?
EDIT
I just noticed it has something to do with lazy loading. The EntityReference(T) is coming with the IsLoaded property set to false and the explicit call of the Load method solves the problem. The problem is that the method RelationshipManager.GetRelatedReference
that is called when the navigation property is accessed should load the EntityReference. Should'nt it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此问题是由
LazyLoadingEnabled
属性的含义引起的。乍一看,LazyLoadingEnabled = false 似乎意味着 EF 在加载对象时会加载对象关系,当然有一些限制以防止 EF 加载整个数据库。实际上,这意味着关系将永远被隐式加载。也就是说:从
N->1
方向,返回的EntityReference(T)
将有一个正确的EntityKey
,但是IsLoaded< /code> 将为 false,
Value
将为 null。另一方面,在方向 1->N
中,集合将为空,IsLoaded
将为 false。可以使用Load
方法显式加载EntityReference
或EntityCollection
。LazyLoadingEnabled
= true,另一方面,意味着它似乎意味着。这些关联将在需要时加载。默认值是 false,这顺便触发了我经历的所有这些混乱。
为了防止混淆,也许应该有一个名为
LoadingMode
的属性,它是一个具有有意义值的枚举。例如:无
、懒惰
、渴望
This problem is because of the meaning of the
LazyLoadingEnabled
property.At first glance,
LazyLoadingEnabled
= false seems to mean that EF will load the object relationships when the object is loaded, of course with some limitations to prevent EF to load the entire database. Actually, it means that the relationships will never be implitly loaded. That is: from thedirection N->1
, the returnedEntityReference(T)
will have a correctEntityKey
butIsLoaded
will be false andValue
will be null. In the other hand, in thedirection 1->N
, the collection will be empty,IsLoaded
will be false. Either theEntityReference
or theEntityCollection
can be explicitly loaded using theLoad
method.LazyLoadingEnabled
= true, in the other hand, means that it seems to mean. The associations will be loaded as they are needed.The default is false, which by the way triggered all this confusion I went through.
To prevent confusions, maybe there should be a property called
LoadingMode
which would be an enum with meaningful values. Like:None
,Lazy
,Eager