ArticleDirectory
- 4.9.1 pre-load
- 4.9.2 delayed Loading
- 4.9.3 manual delayed Loading
- 4.9.4 select the Loading Method
4.9 Load (fetching)
Pre-loading refers to loading all objects and associated data in a query. The attached object is loaded when the delayed loading command is executed. Pre-loading is the most efficient way to retrieve data. Although it retrieves all the data from the database, it only accesses the database once, avoiding the frequent communication between delayed loading and the database.
4.9.1 pre-load
A special method of preloading through the objectquery class: include implementation. This method accepts a string indicating the navigation attribute to be loaded. This string is called a navigation path because it allows you to load the entire related object graph, not just the attributes associated with your query.
Let's start with the simplest example: querying orders with detailed information:
VaRResult =FromOInCTX. Orders. Include ("Orderdetails")SelectO;
Orderdetails is an attribute of the Order class. As we said, the include string parameter is the path where you can load a complete attribute chart. This adds detailed information data to the search order, even if it is useful for every product related to them. You only need to create a path to separate the attributes with dots.
VaRResult =FromOInCTX. Orders. Include ("Orderdetails. Product")SelectO;
The include method returns an instance of objectquery <t>, which means it can be linked with other include and LINQ to entities methods called.
The followingCodeFragment loads the order and their details, and links to another include to load the customer:
VaRResult =FromOInCTX. Orders. Include ("Orderdetails. Product"). Include ("Customer")SelectO;
This query takes significant time to execute, and it is returned to the application.ProgramA large amount of repeated data (because join is generated in SQL code ). There is no need to show the SQL code so that you can understand how complicated it is. Of course, the more objects you load in advance, the more complex the query will be, the longer the execution time will be, and the more data transmitted over the network.
Note:
You can see that the include method can be used together with all the methods you have seen so far. However, we strongly recommend that you put include at the beginning of the query for two reasons. First, the query is more intuitive. Second, include belongs to the objectquery <t> class. However, the LINQ extension method returns ienumerable <t>. This means that you can no longer use include if you have applied the LINQ method, unless you show that ienumerable <t> is converted back to objectquery <t>.
What kind of data is loaded by One-to-multiple associations, and how is the data formed? The first answer is that all associated data is retrieved. If you load the details of an order in advance, there is no way to filter them. LINQ to entities allows you to apply conditions to pre-loaded data, but is ignored. Data cannot be sorted or projected. If you need to apply any modifications to the associated data, You have to resort to projection the entire query.
Note:
Include is an SQL statement translated into outer join. Assume that you need the order and detailed information. If an order does not have any details, you always get the order. This is the correct action, because what you are looking for is the order.
It is too heavy to retrieve data during a round-trip process. You can try to retrieve data as needed. This is what delays loading.
4.9.2 delayed Loading
Delays loading a list of associated entities or entities. You do not need to learn new things. You can access the navigation property to obtain related entities.
Suppose that you retrieve all the orders, the details need to be illusory. If you do not get them in advance, you can access them by traversing orderdetails. This is the same as the navigation attribute that you access pointing to a single object. For example, if you want to retrieve customer information, you can access the customer attributes.
Foreach(VaROrderInCTX. Orders ){Console. Writeline (order. orderid +""+ Order. Customer. Name );Foreach(VaRDetailInOrder. orderdetails ){Console. Writeline (detail. orderdetailid +""+ Detail. Quantity );}}
Note:
Delayed loading is enabled by default. You can disable contextoptions. lazyloadingenabled by setting the context attribute to true. More importantly, objects must be appended to the context During Delayed loading. If you access the navigation attribute of an object and the object is out of the context scope of the generated object, you will get an invalidoperationexception.
How can I trigger a query for simple access to the property getter? How does this happen if you have read the property code without tracking this function? Do you still remember the proxy mentioned in chapter 3rd? It is the answer to these questions.
When the context creates a proxy class, it detects all the attributes of the other object. For each of them, if virtual is marked, the context will overwrite getter and inject the necessary code to execute a query to retrieve data from the database. If the attribute cannot be overwritten, the agent cannot inject code, and delayed loading cannot be activated. Of course, if you disable proxy generation, the normal class will be returned, without proxy, without delayed loading.
Shows a code to simplify delayed loading of internal proxies
Delayed loading is useful, but in some cases you cannot rely on it because you may have disabled proxy generation or outside the context. Don't be disappointed. EF can still provide help.
4.9.3 manual delayed Loading
Manual delayed loading is a way to Dynamically Retrieve an attribute without using delayed loading. This function is implemented by the loadproperty method of the object context. It has two versions: generic and non-generic.
As a generic parameter, attributes of entity types accepted by the generic version must be retrieved in the database. Then, the object is added with a Lambda expression of the property to be loaded:
VoidLoadproperty <t> (T entity,Expression<Func<T,Object> Selector );
Non-generic versions accept two parameters. One is an object, and the other is an attribute to be loaded:
VoidLoadproperty (ObjectEntity,StringNavigationproperty );
The following lists the detailed information for manually loading each order:
// Generic searchCTX. loadproperty <Order> (Order, O => O. orderdetails );// Non-generic searchCTX. loadproperty (order,"Orderdetails");
To make loadproperty work, the primary object must be appended to the context. If it is outside the context, you can create a new one, attach the object to it, and then load the attribute.
In a layered architecture, you can place this method in a lower-layer structure so that data access remains encapsulated. Let's look at an example:
Public voidLoadproperty <t> (T entity,Expression<Func<T,Object> Selector)WhereT:Class{Using(VaRCTX =NewOrderitentities() {CTX. createobjectset <t> (). Attach (entity); CTX. loadproperty <t> (entity, selector );}}
These are the issues you need to know about EF loading.
4.9.4 select the Loading Method
Selecting the correct loading policy varies greatly in a program. In general, the development of applications does not keep this in mind. In the end, you can use a large amount of queries to load all data or use a small amount of queries to retrieve relevant data at runtime.
The second case is the most dangerous. We have seen that only applications that retrieve the primary entity are loaded at runtime. Everything works because of transparent delays in loading. But at least the performance is poor, if not a disaster.
Generally, preload is better. However, you may find that you must load the associated entities in some cases. For example, you may only want to load detailed information for orders in the past seven days. In this case, loading detailed information as needed may be a good choice. Worse, the pre-loaded SQL statements do not always do well. In some cases, the SQL statements generated by EF contain useless Outer Join commands or more columns than the ones to be retrieved.
Determining the correct crawling policy is a test problem and case-by-case analysis is required.
Last words
Chapter 4 is over. Chapter 5 is paused. I will summarize the previous knowledge and use colorbox to write an example.