The hierarchical (tree-like) data model includes a set of records with a parent-child relationship. The nesting depth is not limited.
The hierarchical model is represented by the !Tree
object type.
For the tree to work properly, each record must have three required fields:
!Id
- record identifier!ParentId
- parent record identifier.!Items
- an array of child fields.Note. The T-SQL recursive query engine (CTE) - Common Table Expressions and the WITH clause - is usually used to generate record sets. For more information, see the Microsoft documentation.
The trees can be loaded both statically (the entire tree in one request), and dynamically (lazy loading), when the branches of the tree are filled from the database only in case the user (or program) expands this branch.
Working with a hierarchical model is easiest to demonstrate with an example. Let
there be a table Agents
of the following form:
Id | Parent | Name |
---|---|---|
10 | null | Agent 1 |
20 | null | Agent 2 |
100 | 10 | Subagent 1.1 |
110 | 10 | Subagent 1.2 |
200 | 20 | Subagent 2.1 |
210 | 20 | Subagent 2.2 |
The static tree is completely filled at once in one access to the database. The query that generates data for the tree model will look as follows:
When this set is being processed, a simple array of Agents
items of TAgent
type is created. Each item of this array will contain an Items
array that will be
populated with child items. The parent item is defined by the property with the ParentId
.
modifier. Note that this field does not have a property name, so it will not be included in the resulting model.
As a result of processing, such model will be obtained (service properties for simplicity are not shown):
To work with such a model, the TreeView control is most often used.
Example (XAML):
Dynamic tree fills up as the user opens certain branches of the tree.
When working with a dynamic tree, it is sufficient to return only the top level
of the tree from the loading procedure. However, in order for the system to know
which items can be disclosed, you need to have another service property in the model
with a special !HasChildren
type. If this property is set, the system
assumes that this item has children and shows the corresponding user interface elements.
Note that such a property, even though it is a service property, must have a name, as it is handled on the client’s side.
When a user attempts to open such a tree item, a stored procedure with the
.Expand
suffix is called, which should return the child items
for that node. The process is then repeated recursively.
The top-level procedure can return the following set:
Then, upon an attempt to open the tree, the .Expand
procedure will be called, which should return the elements of the next level of the tree.
The tree items in the data model implement the ITreeElement
interface and have some additional properties. Learn more....