What is the difference between Lazy Loading and Load()
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?
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)
This post on Working with Lazy Loading in EF 4 Code First should also help with understanding how Entity Framework behaves both with and without lazy loading enabled. It also demonstrates that it is enabled by default in EF4 and how to disable it on a per-instance or by default for your application basis.
精彩评论