为什么不能从EntityObject获取ObjectContext众所周知,如果我们有一个EntityObject,我们是找不到它所属的ObjectContext的。我想这很公平,但是为什么我们可以延迟加载对象呢?延迟加载的过程肯定必须访问ObjectContext才能加载新对象吗?实际上,您可以从EntityObject获取ObjectContext:它在此处进行了描述。您是对的,给定一个对象,我们不知道它属于哪个上下文,或者它附加到哪个会话。但是延迟加载是这样发生的:varfirstPost=_Context.Posts.First()varcommentList=firstPost.Comments当你说_Context.Posts.First()然后加载一个帖子。然后当你说firstPost.Comments时,载入评论列表。这是可能的,因为Post中的Comments字段可能是IList类型或某个通用接口:这是因为EF4可以放置代理列表而不是实际的评论列表。代理列表知道_Context-知道它附加到哪个会话或上下文。因此,它能够按需加载实际列表。接受的答案是有限的,因为它仅在实体至少具有一种关系时才有效。但是,这也可以通过反射来完成:publicObjectContextContext(EntityObjectentity){varrelationshipManager=((IEntityWithRelationships)entity).RelationshipManager;varwrappedOwnerProperty=relationshipManager.GetType().GetProperty("WrappedOwner",BindingFlags.Instance|BindingFlags.NonPublic);varwrappedOwner=wrappedOwnerProperty.GetValue(relationshipManager);varcontextProperty=wrappedOwner.GetType().GetProperty("上下文");返回(ObjectContext)contextProperty.GetValue(wrappedOwner);}在VB.NET中:FunctionContext(entityAsEntityObject)AsObjectContextDimrelationshipManager=DirectCast(entity,IEntityWithRelationships).RelationshipManagerDimwrappedOwnerProperty=relationshipManager.GetType.GetProperty("WrappedOwner",BindingFlags.InstanceOrBindingFlags.NonPublic)ReturnwrappedOwnerProperty.GetValue(relationshipManager).ContextEndFunction注意:这是在.NETFrameworkv.4.5.1下测试的。YMMV,因为这取决于内部WrappedOwner属性和内部BaseEntityWrapper类的Context属性。但是,如果早期版本的.NET具有不同的内部属性/类,那么执行类似操作应该足够简单。注意:这可以通过使它成为EntityObject的扩展方法并使用泛型参数返回强类型的ObjectContext来进一步改进。它也可以通过使用某种方法按名称获取属性值来简化。以上就是C#学习教程:为什么我们不能从EntityObject中得到ObjectContext共享的所有内容?侵权请点击右侧联系管理员删除。如需转载请注明出处:
