Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

c# - why can't we get ObjectContext from an EntityObject

It is well know that if we have an EntityObject that there is no way to find the ObjectContext that it belongs to. That's fair enough I guess, but why is it that we can lazy load objects then? Surely the process of lazy loading has to get access to the ObjectContext in order to load the new objects?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are right, given an object, we don't know what context it belongs to, or what session it is attached to. But Lazy Loading happens like this :

var firstPost = _Context.Posts.First()
var commentList = firstPost.Comments

When you say _Context.Posts.First() then one post is loaded. Then when you say firstPost.Comments that's when the comments list is loaded.

This is possible because the type of your Comments field in your Post is probably an IList or some such generic interface : this is because EF4 can put a proxy list instead of the actual comment list. The proxy list knows about the _Context - knows about which session or context it is attached to. Hence it is able to load an actual list on demand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...