EntityFramework delayed Loading
Delayed loading: load (read) only when we need to use it)
When we want to view the order information, we want to use delayed loading to display the detailed records of the corresponding order. This not only accelerates the reading efficiency, it also avoids loading unnecessary data. Delayed loading is usually used when foreach reads data cyclically.
In EF, delayed loading is supported because query is performed and DbQuery class is returned.
To demonstrate delayed loading, use SQL server profiler to query data.
SQL server profiler is used to monitor SQL connection execution. Create a new trail.
When we use the DbContext class to operate EF:
The query has been completed, but the query tracker is empty:
EF executes SQL statements only when query results are used.
EF pairs map objects to databases. In fact, you just need to operate the database directly on the entity.
It is more in line with the object-oriented thinking.
The idea of direct loading:
1. Declare Variables
2. Conditions to be queried
3. Query Based on query conditions and store the results in variables.
When used, you can directly use the variable.
The idea of delayed loading:
1. Declare Variables
2. Enter the conditions to be queried.
When used, take all the variables and conditions, and use them after execution.
The two ideas are used to handle different situations. It is the same as true/false paging.
1. If you load data in a foreach loop, it is better to use delayed loading because you do not need to read all the data at once, this may cause n queries to the database, but it is basically within the acceptable range.
2. If all data needs to be loaded at one time during development, including all data in the associated table, it is better to use greedy loading, however, this method may cause efficiency problems, especially when the data volume is large.