views:

84

answers:

1

In Entity Framework 4, what is the difference between Lazy Loading, and using Load() method?

Edit: I have added, two 'if' statements:

Lazy Loading:

var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
     if ( contact.ID == 5 )
        Console.WriteLine( contact.Addresses.City );
}

Load() method:

context.ContextOptions.LazyLoadingEnabled = false;

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 );
     }
}

Now, having this two 'if' checks, why should I preffer one before another?

+2  A: 

Lazy Loading means that a load will only occur once the object is needed, thus not loading unnecessary data.

When you disable Lazy Loading you say that you will load yourself by calling load.

http://en.wikipedia.org/wiki/Lazy_loading

Lazy Loading is disabled by default, so when you set it to false in your first line it does not do anything.

When you call Load, you will load all the related objects to that database (which is not needed in this case which makes it work without it)

Oskar Kjellin
@Oskar Kjellin, I have added two 'if' statements, to my original question, does Lazy Loading and Load() are still not equivalent? Or should I assume, that Lazy Loading is implicit, and Load() is explicit way of doing same thing.
kofucii
@Kofucii why would you want to do anything like that? Must be really slow
Oskar Kjellin
@Oskar Kjellin, It is not a question of 'Why'. I'm just trying to understand the principles behind this two features. Why I have this two models, wich looks to do same thing.
kofucii
@Kofucii please see my edit
Oskar Kjellin
@Oskar Kjellin, in EF 4, Lazy Loading is set to true by default.
kofucii
@Kufucii That does not seem to be the entire truth, please check this link http://msdn.microsoft.com/en-us/library/bb896272.aspx
Oskar Kjellin
@Oskar Kjellin, You are right. I didn't know that.
kofucii