Eager , Lazy and explicit loading in EF6

后端 未结 3 1209
我寻月下人不归
我寻月下人不归 2020-11-30 01:02

I have read this tutorial and this article but I don\'t understand exactly the use of each loading type.

I Explain

I have this POCO :

<
3条回答
  •  攒了一身酷
    2020-11-30 01:44

    Question 1 and 2:

    Your explanation of lazy loading and eager loading is correct.
    The use of explicit loading is a bit different than you described.

    EntityFramework returns IQueryable objects, which essentially contain the query to the database. But these are not executed until the first time they are enumerated.
    Load executes the query so that its results are stored locally.
    Calling Load is the same as calling ToList and throwing away that List, without having the overhead of creating the List.

    Question 3:

    If you use lazy loading, EntityFramework will take care of loading the navigation property for you, so you won't get an exception.
    Keep in mind that this can take a while and make you application unresponsive.

    Question 4:

    In disconnected cases (e.g. network application) you can't use lazy loading, because these objects are translated into DTOs and then not tracked by EntityFramework.

    Also, if you know you're going to use a navigation property, its good practice to load it eagerly, so you don't have to wait until they are loaded from the database.
    For example, lets say you store the result in a list and bind it to a WPF DataGrid. If the DataGrid accesses a property that is not loaded yet, the user experiences a noticeable timeout until that property is displayed. Additionally the application will not respond during the loading time (if you dont load asynchronously).

提交回复
热议问题