I read this What is the difference between Lazy Loading and Load() thread to understand difference between using Load meth开发者_如何学运维od and Lazy loading in entity framework. But in that example using lazy loading and Load method have the same effect. Can you plz give me an example to understand where to use lazy loading and where to use Load method?
If we assume Lazy Loading is off, and the Addresses weren't in an Include method the following bit of code would raise an exception because the Addresses would be empty.
var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
if ( contact.ID == 5 ) {
Console.WriteLine( contact.Addresses.City );
}
}
Adding the Load call:
var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
if ( contact.ID == 5 ) {
contact.Addresses.Load()
Console.WriteLine( contact.Addresses.City );
}
}
Explicitly loads the addresses and would therefore prevent an exception.
If Lazy Loading is on the first block of code would not raise an exception either because EF will load Addresses for you - without making any explicit calls.
I hope that helps a bit...
Lazy loading is actually calling Load
method even we also use explicit loading for that because you must call Load
method manually. What is usually used as lazy loading in EFv4+ should be called transparent lazy loading. That means that you don't have to do any special call and EF will load relation for you.
EF uses dynamic proxies for lazy loading. These proxies are types derived from entities and created at runtime. I didn't see the code of these proxies but I believe that they actually call Load
in property getter if the backing field is null
.
精彩评论