Include delayed loading and greedy loading, include delayed Loading
Greedy loading:Gu mingyu is to read all the things to be loaded once.
Using (var context = new MyDbContext () {var orders
{Var orders = from o in context. Orders. Include ("OrderDetails") select o;
}
When reading the order information orders, we want to read the Order details, so here we useIncludeKeyword to load the joined table.
Delayed loading:Load (read) only when necessary)
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.
When defining a Model, we need to add the virtual keyword before the attribute. As follows:
Public class Order {public int OrderID {get; set;} public string OrderTitle {get; set;} public string CustomerName {get; set;} public DateTime TransactionDate {get; set ;} public virtual List <OrderDetail> OrderDetails {get; set ;}}
If we want to disable the use of delayed loading, the best way is to declare it in the DbContext class constructor.
Public class MyDbContext: DbContext
{
Public MyDbContext () {this. Configuration. LazyLoadingEnabled = false ;}
}
Summary:
Greedy loading: 1. Reduces data access latency and returns all data during a database access. 2. One-time reading of all relevant data may result in some data not needing to be used, resulting in slow reading speed and low efficiency.
Delayed loading: 1. loading is performed only when the associated data needs to be read. 2. Performance may be reduced due to the delay in Data Access. Because in a loop, each piece of data will access the database once, resulting in increased database pressure
In summary, we should be clear about which mechanism should we use? My personal suggestion is:
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.