Generated code - Prefetch Paths

Preface

SelfServicing supports load-on-demand, also known as 'lazy loading'. Load-on-demand means that a related entity, or set of related entities are loaded when you ask for it. A typical example is loading a customer objects' Order objects in its Orders collection not when you instantiate the customer entity but when you reference the Orders collection:

// C#
CustomerEntity customer = new CustomerEntity("CHOPS");
// no Orders are loaded at this point
OrdersCollection orders = customer.Orders;
// orders of the customer "CHOPS" are now loaded.
' VB.NET
Dim customer As New CustomerEntity("CHOPS")
' no Orders are loaded at this point
Dim orders As OrdersCollection = customer.Orders
' orders of the customer "CHOPS" are now loaded.

This can be very efficient in some scenario's, for example if you load a collection of customer entities and you want the Order entities of just one customer, you save the time fetching the other customers' Order entities. However there are scenario's in which this is terribly inefficient. Say you want a collection of Order entities and also want to fetch their related Customer entities. Using lazy loading this would require for 50 order entities 51 queries: 1 for the Order entities and 50 for each Customer. This is solved by Prefetch Paths, which allow you to specify which objects to fetch together with the actual objects to fetch, using only one query per node in the path (here: 2 queries). Once data is fetched through a Prefetch Path, load-on-demand for that related entity or entity collection is switched off, unless you set the always fetch flag for that particular related entity or set of related entities to true.

This section describes how to use Prefetch Paths and how they work internally.

note Note:
If your database is case insensitive (uses case insensitive collation), and you have foreign key values which only differ in casing from the PK values, it can be that the prefetch path merging (merge child (e.g. order) with parent (e.g. customer) doesn't find matching parent-child relations, because the FK differs from the PK value (as the routine uses case sensitive compares).

To fix this, set the static / shared property EntityFieldCore.CaseSensitiveStringHashCodes to false (default is true). You can also do this through a config file setting by specifying caseSensitiveStringHashCodes with 'false' in the .config file of your application. See for more information about this config file setting Application Configuration through .config files.

Using Prefetch Paths, the basics

In the Preface paragraph, the example of an Order selection and their related Customer objects was mentioned. The most efficient way to fetch all that data would be: 2 queries, one for all the Order entities and one for all the Customer entities. By specifying a Prefetch Path together with the fetch action for the Order entities, the logic will fetch these related entities defined by the Prefetch Path as efficient as possible and will merge the two resultsets to the result you're looking for. PrefetchPath objects are created for a single entity type, specified by the specified entity enumeration. This ensures that PrefetchPathElements added to the PrefetchPath object actually define a valid node for the entity the path belongs to.

PrefetchPathElements, the nodes added to the PrefetchPath objects which define the entities to fetch, are created using static (shared) properties of the parent entity. The properties are named after the fields mapped on the relations they define the fetch action for. Example: The Orders collection in a Customer entity can be fetched using a Prefetch Path by using the static (shared) property PrefetchPathOrders of the CustomerEntity class to produce the PrefetchPathElement for 'Orders'. This way, it is easy to see which PrefetchPathElement producing property you have to use to produce the right PrefetchPathElement.

The example of Order entities and their related Customer entities fetched with Prefetch Paths looks like this:

// C#
OrderCollection orders = new OrderCollection();
IPrefetchPath prefetchPath = new PrefetchPath((int)EntityType.OrderEntity);
prefetchPath.Add(OrderEntity.PrefetchPathCustomer);
IPredicateExpression filter = new PredicateExpression();
filter.Add(OrderFields.EmployeeId == 2);
orders.GetMulti(filter, prefetchPath);
' VB.NET
Dim orders As New OrderCollection()
Dim prefetchPath As IPrefetchPath = New PrefetchPath(CType(EntityType.OrderEntity, Integer))
prefetchPath.Add(OrderEntity.PrefetchPathCustomer)
Dim filter As IPredicateExpression = New PredicateExpression()
filter.Add( OrderFields.EmployeeId = 2)
orders.GetMulti(filter, prefetchPath)

This fetch action will fetch all Order entities accepted by the Employee with Id 2, and will also fetch for each of these Order entities the related Customer entity. This will result in just two queries: one for the Order entities with the filter on EmployeeId = 2 and one for the Customer entities with a subquery filter using the Order entity query. The fetch logic will then merge these two resultsets using efficient hashtables in a single pass algorithm.

The example above is a rather simple graph, just two nodes. LLBLGen Pro's Prefetch Path functionality is capable of handling much more complex graphs and offers options to tweak the fetch actions per PrefetchPathElement to your liking. To illustrate that the graph doesn't have to be linear, we'll fetch a more complex graph: a set of Customer entities, all their related Order entities, all the Order's Order Detail entities and the Customer entities' Address entities. The example illustrates how to use sublevels in the graph: use the SubPath property of the PrefetchPathElement object used to build graph nodes with.

// C#
CustomerCollection customers = new CustomerCollection();
IPrefetchPath prefetchPath = new PrefetchPath((int)EntityType.CustomerEntity);
prefetchPath.Add(CustomerEntity.PrefetchPathOrders).SubPath.Add(OrderEntity.PrefetchPathOrderDetails);
prefetchPath.Add(CustomerEntity.PrefetchPathVisitingAddress);
IPredicateExpression filter = new PredicateExpression();
filter.Add(CustomerFields.Country == "Germany");
customers.GetMulti(filter, prefetchPath);
' VB.NET
Dim customers As New CustomerCollection()
Dim prefetchPath As IPrefetchPath = New PrefetchPath(CType(EntityType.CustomerEntity, Integer))
prefetchPath.Add(CustomerEntity.PrefetchPathOrders).SubPath.Add(OrderEntity.PrefetchPathOrderDetails)
prefetchPath.Add(CustomerEntity.PrefetchPathVisitingAddress)
Dim filter As IPredicateExpression = New PredicateExpression()
filter.Add(New FieldCompareValuePredicate(CustomerFields.Country, ComparisonOperator.Equal, "Germany"))
customers.GetMulti(filter, prefetchPath)

The example above, fetches in 4 queries (one for the Customer entities, one for the Order entities, one for the Order Detail entities and one for the Address entities) all objects required for this particular graph. As the end result, you'll get all Customer entities from Germany, which have their Orders collections filled with their related Order entities, all Order entities have their related Order Detail entities loaded and each Customer entity also has their visiting address entity loaded. The graph is also non-linear: it has two branches from Customer. You can define more if you want, there is no limit set on the number of PrefetchPathElements in a Prefetch Path, however consider that each level in a graph is a subquery, so if you have for example a Prefetch Path with a subpath of a length of 7 PrefetchPathElements nested into eachother, you'll get 7 subqueries nested into each other.
Optimizing Prefetch Paths
The LLBLGen Pro runtime libraries create for a Prefetch Paths per node a sub-query, to be able to filter child nodes on the query results of the parent nodes. Say, you want to fetch all customers from "France" and their order objects. This would look something like the following:

// C#
IPrefetchPath path = new PrefetchPath((int)EntityType.CustomerEntity);
path.Add(CustomerEntity.PrefetchPathOrders);
' VB.NET
Dim path As IPrefetchPath = New PrefetchPath(CInt(EntityType.CustomerEntity))
path.Add(CustomerEntity.PrefetchPathOrders);

When the customers are fetched with the filter and the path, using CustomerCollection.GetMulti(), it will produce SQL like the following: (pseudo)
Query to fetch the customers:

SELECT CustomerID, CompanyName, ...
FROM Customers
WHERE Country = @country

Query to fetch the orders:

SELECT OrderID, CustomerID, OrderDate, ...
FROM Orders
WHERE CustomerID IN
(
	SELECT CustomerID
	FROM Customers
	WHERE Country = @country
)

Tests will show that for small quantities of Customers, say 10, this query is less efficient than this query: (pseudo)

SELECT OrderID, CustomerID, OrderDate, ...
FROM Orders
WHERE CustomerID IN
( @customer1, @customer2, ... , @customer10)

LLBLGen Pro offers you to tweak this query generation by specifying a threshold, DaoBase.ParameterisedPrefetchPathThreshold, what the runtime libraries should do: produce a subquery with a select or a subquery with a range of values. The value set for ParameterisedPrefetchPathThreshold specifies at which amount of the parent entities (in our example, the customer entities) it has to switch to a subquery with a select. ParameterisedPrefetchPathThreshold is set to 50 by default. Tests showed a threshold of 200 is still efficient, but to be sure it works on every database, the value is set to 50.

Please note that for each subnode fetch, it's parent is the one which is examined for this theshold, so it's not only the root of the complete graph which is optimized with this setting. In the example in the previous paragraph, Customer - Orders - OrderDetails was fetched, and for OrderDetails the node for Orders is the parent node and the entities fetched for orders are the parent entities for the orderdetails entities.

You're adviced not to set the ParameterisedPrefetchPathThreshold to a value larger than 300 unless you've tested a larger value in practise and it made queries run faster. This to prevent you're using slower queries than necessary. The setting is global, so after setting the threshold, it affects all prefetch path related fetches of the application.
Polymorphic Prefetch Paths
Because inheritance would be quite useless if polymorphism wouldn't be possible, LLBLGen Pro supports polymorphism in prefetch path technology as well. Polymorphic prefetch paths work the same as normal prefetch paths, only now they work on subtypes as well. Say you have the following hierarchy: Employee - Manager - BoardMember and BoardMember has a relation with CompanyCar (which can be a hierarchy of its own). If you then fetch all employees (which can be of type BoardMember) and you want to load for each BoardMember loaded in that fetch also its related CompanyCar, you define the prefetch path as you'd expect:

// C#
EmployeeCollection employees = new EmployeeCollection();
IPrefetchPath prefetchPath = new PrefetchPath((int)EntityType.EmployeeEntity);
// specify the actual path: BoardMember - CompanyCar
prefetchPath.Add(BoardMemberEntity.PrefetchPathCompanyCar);
// .. fetch code
' VB.NET
Dim employees As New EmployeeCollection()
Dim prefetchPath As IPrefetchPath = New PrefetchPath(CInt(EntityType.EmployeeEntity))
' specify the actual path: BoardMember - CompanyCar
prefetchPath.Add(BoardMemberEntity.PrefetchPathCompanyCar)
' .. fetch code

LLBLGen Pro will then only load those CompanyCar entities which are referenced by a BoardMember entity, and will merge them at runtime with the BoardMember entities loaded in the fetch.
Multi-branched Prefetch Paths
Prefetch Paths can also be multi-branched. Multi-branched means that two or more subpaths are defined from the same path node. As Prefetch Paths are defined per-line this can be a bit of a problem. The example below defines two subpaths from the OrderEntity node and it illustrates how to create this multi-branched Prefetch Path definition:

PrefetchPath path = new PrefetchPath((int)EntityType.CustomerEntity);
IPrefetchPathElement orderElement = path.Add(CustomerEntity.PrefetchPathOrders);
orderElement.SubPath.Add(OrderEntity.PrefetchPathOrderDetails);  // branch 1
orderElement.SubPath.Add(OrderEntity.PrefetchPathEmployee);      // branch 2
Dim path As New PrefetchPath(CInt(EntityType.CustomerEntity))
Dim orderElement As IPrefetchPathElement = path.Add(CustomerEntity.PrefetchPathOrders)
orderElement.SubPath.Add(OrderEntity.PrefetchPathOrderDetails)  ' branch 1
orderElement.SubPath.Add(OrderEntity.PrefetchPathEmployee)      ' branch 2

Advanced Prefetch Paths

The previous examples showed some of the power of the Prefetch Path functionality, but sometimes you need some extra features, like filtering on the related entities, sorting of the related entities fetched and limiting the number of related entities fetched. These features are available in the PrefetchPathElement object, and also accessable through overloads of the PrefetchPath.Add() method. Let's say you want all employees and the last order they processed. The following example illustrates this, using Prefetch Paths. It sorts the related entities, and limits the output to just 1.

// C#
EmployeeCollection employees = new EmployeeCollection();
IPrefetchPath prefetchPath = new PrefetchPath((int)EntityType.EmployeeEntity);
ISortExpression sorter = new SortExpression();
sorter.Add(OrderFields.OrderDate | SortOperator.Descending);
prefetchPath.Add(EmployeeEntity.PrefetchPathOrders, 1, null, null, sorter);
employees.GetMulti(null, prefetchPath);
' VB.NET
Dim employees As New EmployeeCollection()
Dim prefetchPath As IPrefetchPath = New PrefetchPath(CInt(EntityType.EmployeeEntity))
Dim sorter As ISortExpression = New SortExpression()
sorter.Add(New SortClause(OrderFields.OrderDate, SortOperator.Descending))
prefetchPath.Add(EmployeeEntity.PrefetchPathOrders, 1, Nothing, Nothing, sorter)
employees.GetMulti(Nothing, prefetchPath)

Besides a sort expression, you can specify a RelationCollection together with a PredicateExpression when you add a PrefetchPathElement to the PrefetchPath to ensure that the fetched related entities are the ones you need.

For example, the following code snippet illustrates the prefetch path of Customer - Orders, but also filters the customers on its related orders. As this filter belongs to the customers fetch, it shouldn't be added to the Orders node, but should be passed to the GetMulti() method call.

// C#
CustomerCollection customers = new CustomerCollection();
PredicateExpression customerFilter = new PredicateExpression();
RelationCollection relations = new RelationCollection();
// fetch all customers which have orders shipped to brazil.
relations.Add(CustomerEntity.Relations.OrderEntityUsingCustomerId);
customerFilter.Add(OrderFields.ShipCountry=="Brazil");
// load for all customers fetched their orders. 
PrefetchPath path = new PrefetchPath(EntityType.CustomerEntity);
path.Add(CustomerEntity.PrefetchPathOrders);
// perform the fetch customers.GetMulti(customerFilter, 0, null, relations, path);
' VB.NET
Dim customers As New CustomerCollection()
Dim customerFilter As New PredicateExpression()
Dim relations As New RelationCollection()
' fetch all customers which have orders shipped to brazil.
relations.Add(CustomerEntity.Relations.OrderEntityUsingCustomerId)
customerFilter.Add(OrderFields.ShipCountry="Brazil")
' load for all customers fetched their orders. 
Dim path As new PrefetchPath(EntityType.CustomerEntity)
path.Add(CustomerEntity.PrefetchPathOrders)
' Perform the fetch customers.GetMulti(customerFilter, 0, Nothing, relations, path)

M:N related entities
Prefetch Paths can also be used to fetch m:n related entities, they work the same as other related entities. There is one caveat: the intermediate entities are not fetched with an m:n relation Prefetch Path. For example, if you fetch a set of Customer entities and also their m:n related Employee entities, the intermediate entity, Order, is not fetched. If you specify, via another PrefetchPathElement, to fetch the Order entities as well, and via a SubPath also their related Employee entities, these Employee entities are not the same objects as located in the Employees collection of every Customer entity you fetched.

Single entity fetches and Prefetch Paths

Prefetch Paths can also be used when you fetch a single entity, either by specifying a primary key in the constructor or via a unique constraint fetch. Below are two examples, one using the primary key and one using a unique constraint. Both fetch the m:n related Employees for the particular Customer entity instantiated.

Primary key fetch

// C#
IPrefetchPath prefetchPath = new PrefetchPath((int)EntityType.CustomerEntity);
prefetchPath.Add(CustomerEntity.PrefetchPathEmployees);
CustomerEntity customer = new CustomerEntity("BLONP", prefetchPath);
' VB.NET
Dim prefetchPath As IPrefetchPath = New PrefetchPath(CType(EntityType.CustomerEntity, Integer))
prefetchPath.Add(CustomerEntity.PrefetchPathEmployees)
Dim customer As New CustomerEntity("BLONP", prefetchPath)

Unique constraint fetch

// C#
CustomerEntity customer = new CustomerEntity();
IPrefetchPath prefetchPath = new PrefetchPath((int)EntityType.CustomerEntity);
prefetchPath.Add(CustomerEntity.PrefetchPathEmployees);
customer.FetchUsingUCCompanyName("Blauer See Delikatessen", prefetchPath);
' VB.NET
Dim customer As New CustomerEntity()
Dim prefetchPath As IPrefetchPath = New PrefetchPath(CType(EntityType.CustomerEntity, Integer))
prefetchPath.Add(CustomerEntity.PrefetchPathEmployees)
customer.FetchUsingUCCompanyName("Blauer See Delikatessen", prefetchPath)

Prefetch Paths and Paging

Starting with version 1.0.2005.1, LLBLGen Pro supports paging functionality in combination of Prefetch Paths. Due to the complex nature of the prefetch path queries, especially with per-node filters, sort expressions etc., paging wasn't possible, though due to the DaoBase.ParameterisedPrefetchPathThreshold threshold setting (See earlier in this section: Optimizing Prefetch Paths), paging can be made possible. If you want to utilize paging in combination of prefetch paths, be sure to set DaoBase.ParameterisedPrefetchPathThreshold to a value larger than the page size you want to use. You can use paging in combination of prefetch path with a page size larger than DaoBase.ParameterisedPrefetchPathThreshold but it will be less efficient.

To use paging in combination of prefetch paths, use one of the overloads you'd normally use for fetching data using a prefetch path, which accept a page size and page number as well.

LLBLGen Pro v3.0 documentation. ©2010 Solutions Design