Skip to content

Creating Your First Entity Tree

David West edited this page Aug 26, 2016 · 6 revisions

< Entity Tree Overview

Let's jump right into creating an entity tree. Our example will use the built-in concrete ReadOnlyEntityTreeNode<TId, TItem> class. To populate this tree, we'll use our previously-defined "data" tree as the source. Recall, this is composed of our custom CategoryDataNode objects.

First, let's define a core entity type.

public class Category
{
    public Category(int categoryId, string name)
    {
        CategoryId = categoryId;
        Name = name;
    }
         
    public int CategoryId {get;}
    public string Name {get;}
}

Assuming the variable dataRoot holds our CategoryDataNode source root, let's create a core root entity object:

var rootItem = new Category(dataRoot.Id, dataRoot.Name);

Next, we create our target root node:

var root = new ReadOnlyEntityTreeNode<int, Category>(c => c.CategoryId, rootItem);

Let's examine the type parameters. Note the similarity between this type signature and the .NET Dictionary<TKey, TValue> signature.

  • The first type parameter indicates that our entity has an id of type int.
  • The second type parameter indicates that our core entity type is Category.

Now a brief explanation about the constructor parameters.

The constructor we used above is one of two possible constructors. The alternate constructor uses the IEntityDefinition<TId, TItem> interface which we'll discuss in the section Entity Definitions. For now, we're choosing this constructor for simplicity.

  • The first parameter is a selector function; it tells the node how to get the id of a Category object.
  • The second parameter is the root Category object.

So far, we have the root object of the desired type. Now let's build the rest of the tree:

root.Build(dataRoot, dataNode => new Category(dataNode.Id, dataNode.Name);

The Build method allows us to declaratively populate our tree once the root has been established. This is only one of several useful overloads, each which makes it easy to populate a tree from a variety of sources. More on this later.

The parameters are as follows:

  • The first parameter is the source (data) root.
  • The second parameter is a mapping function that instructs the builder how to convert a CategoryDataNode to a Category object.

Now our tree is completely built. Note that because this is a read-only tree, we can no longer invoke Build on the root or any of its descendants; doing so would cause an exception.

Basic Querying >

Clone this wiki locally