What is the difference between Lazy Loading and Load()

穿精又带淫゛_ 提交于 2019-12-10 17:34:40

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/3850163/what-is-the-difference-between-lazy-loading-and-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!