Skip to main content

Entities and relations

Define entity types in the model and connect them with references or indexed relations. The choice determines how clients load related records.

For the team workflow, see Connect products and variants.

Clients can also use editor metadata for labels, hints and dynamic selections on entities and actions.

Entity families​

Use an entity family when several concrete domain types share identity, storage and a query surface, but should not share every property in application code. The family root is abstract and carries the common contract. Every concrete implementation has a stable wire discriminator:

[VoxEntityFamily("Product")]
[VoxRouteName("products")]
public abstract class ProductBase : IVoxEntity
{
// Built-in IVoxEntity properties omitted
public required virtual string ProductNumber { get; set; }
public virtual ProductContent Content { get; set; } = new();
}

[VoxEntityKind("standard")]
public class Product : ProductBase;

[VoxEntityKind("bundle")]
public class BundleProduct : ProductBase
{
public virtual BundleConfiguration Configuration { get; set; } = new();
}

Product remains one Vox entity type: both kinds use the products routes, the same entity table, the same identity space, and one combined set of indexes and constraints. Entity JSON includes "kind": "standard" or "kind": "bundle", and deserializing ProductBase restores the concrete CLR type. Queries return both kinds in one result unless they're narrowed: kind is a built-in query field of every family, so ?kind=bundle lists only bundles and ?sort=kind sorts by kind.

A kind can have its own name and icon, from [Display(Name = ...)] and [VoxIcon] on its class, which an admin UI shows for its entities, eg a different icon for each kind of content block.

The discriminator is structural, not a replacement for a business classification. Give kind names stable domain meaning and do not derive them from a source system. Changing an existing entity from one kind to another is not an update operation; model that as a replacement or as an ordinary property when the distinction is mutable business state.

Common actions are exposed once. Creates are kind-specific and require the kind field, while an action for a derived-only property is offered only for that kind and is rejected for other stored implementations. Query fields, unique constraints, varying properties and relations declared by concrete implementations contribute to the shared physical model; a derived-only field simply has no value for the other kinds. Several kinds can each declare the same field, also under different CLR names with the same [JsonPropertyName], eg Heading in one kind and Name in another for title: it's one field of the family, and a cached reference that several kinds declare is one cached reference, so its kinds must cache the same type and refresh it the same way. An inverse navigation, eg the pages that use an image block, can be declared by one kind only: the other kinds simply don't have it.

Relations normally target the base contract, for example VoxReference<ProductBase>, when every product kind is a valid target. Target a concrete class only when the relation is genuinely restricted to that kind. A CMS can use the same pattern with an abstract CmsBlock and concrete hero, text, products and category-grid blocks: pages reference CmsBlock, while code working with a hero sees only hero properties. Each kind can have a projection factory of its own under one projection name, and every delivered block says which kind it is, so a storefront renders it with a component per kind; see Projections per kind of an entity family.

Relations are declared by reference properties. A single reference uses VoxReference<T>. For a many-reference relation, choose between two kinds, described in Embedded and index-backed collections:

Declared asStoredOrderChanged by
List<VoxReference<T>>in the entity's JSON, and indexedordered, as listedsetting the list, like any other field
IVoxRelationReferences<T>only in the relation indexno meaningful positionLink, Unlink and Replace mutations

The referenced type is authoritative; [VoxRelation] only configures names, expansion and context inheritance.

References and relation attributes may also appear inside nested objects. Their API and query paths include the containing property, for example pim.categories. See Owned and mirrored data for the origins of the fields and their concurrency.

public class Product : IVoxEntity
{
// Built-in IVoxEntity properties omitted

public virtual VoxReference<Brand>? Brand { get; set; }

[VoxRelation(InverseName = "products")]
public virtual List<VoxReference<Category>> Categories { get; set; } = [];
}

Every relation can be filtered by its reference IDs. Vox stores the relation index in both directions, so Brand does not need a products collection merely to expose the inverse relation.

An entity implicitly converts to a reference of its own type, for both owned and external entities. The conversion copies its ID, without embedding the entity or loading anything:

VoxReference<Category> reference = category;
product.Brand = brand;
product.Categories = [category];

// LINQ needs the result type spelled out; Select does not convert a collection of entities into references itself.
product.Categories = categories.Select(category => (VoxReference<Category>)category).ToList();

A null entity becomes a null reference. The declared target must identify one entity type, like the ID-only constructor. For a polymorphic reference that can target several entity types, supply the entity type explicitly with new VoxReference<T>(entity.Id, entityTypeName). C# does not apply user-defined conversions directly from an interface-typed variable; retain the entity's concrete type when using the implicit conversion.

Embedded and index-backed collections​

Use a List<VoxReference<T>> when the complete collection is part of the entity's useful data. The list is serialized in entity JSON, appears in history snapshots, and is also synchronized to the relation index. Reading a product gives you the complete list without another query.

Use IVoxRelationReferences<T> when the collection can contain hundreds or thousands of links, when consumers normally page through it, or when its order doesn't matter. A campaign's products are one example, since a campaign can cover any number of products:

public class ProductPimData
{
[VoxRelation(Name = "categories", InverseName = "products")]
public virtual IVoxRelationReferences<Category> Categories { get; set; } = default!;
}

var count = await product.Pim.Categories.CountAsync(cancellationToken);
var hasJackets = await product.Pim.Categories.ContainsAsync("jackets", cancellationToken: cancellationToken);
var batch = await product.Pim.Categories.LoadBatchAsync(take: 50, cancellationToken: cancellationToken);
var next = await product.Pim.Categories.LoadBatchAsync(take: 50, batch.ContinuationToken, cancellationToken);

An index-backed relation is initialized by Vox when the entity is materialized. It is not serialized in stored JSON, API entity JSON, history snapshots, or search documents, and it cannot be enumerated implicitly. CountAsync, ContainsAsync, and LoadBatchAsync query reference identities without loading the related entities. Use IVoxRelationLoader or the relation API when the related entities themselves are needed.

An index-backed relation has no positions, so it's read in batches instead of by offset. A batch is ordered by the entity type and id of what it refers to, and its ContinuationToken starts the next batch after its last reference, or is null when there's nothing more. Every link that exists throughout the reading is read exactly once, also when other links are added or removed between batches, and in a draft or release the batches are the published links with the changes made there.

The HTTP API has the same distinction:

  • GET /api/{entityType}/{id}/relations/{relationName} loads related entities: a page with skip and take for an embedded relation, and a batch with take and continuationToken for an index-backed one, which returns the token of the next batch. skip is limited to VoxReadBudgets.MaxSkip (10,000) like the offset of a query; read a larger relation with the references endpoint.
  • GET /api/{entityType}/{id}/relations/{relationName}/references loads only the reference identities, in batches with take and continuationToken.

Both endpoints apply read authorization to the owner and every returned target. The reference-only endpoint is the appropriate choice for editors that need to inspect or page a very large selection without hydrating every target.

Index-backed relations use the entity's configured relation storage and participate in drafts, content releases, events, recalculations, and optimistic concurrency. Their links are still available from both directions.

Changing an index-backed relation​

Action and import handlers collect relation changes next to their entity changes. Vox commits both atomically:

[VoxUpdateRelations("categories")]
public class AssignCategories : IVoxUpdate<Product>
{
public IReadOnlyList<VoxReference<Category>> Categories { get; set; } = [];
}

public class AssignCategoriesHandler : IVoxUpdateHandler<AssignCategories, Product>
{
public Task<Product> ApplyAsync(
AssignCategories update,
Product current,
IVoxEntityChanges<Product> changes,
CancellationToken cancellationToken)
{
changes.Relations.Replace(product => product.Pim.Categories, update.Categories);
return Task.FromResult(current);
}
}

Link appends references that are not already linked, Unlink removes references that exist, and Replace makes the supplied distinct references the complete relation. All three are idempotent. A mutation contains identities, not loaded entities, so changing a large relation does not require reading it first.

Mutation order is significant. Vox applies all mutations collected by one handler in call order; for example, a Replace followed by a Link replaces the old set and then appends the additional references. A single mutation must not contain duplicate identities or blank IDs. For polymorphic relations, each reference must also identify its concrete entity type. Vox validates and canonicalizes the identities before writing anything.

The handler does not modify the IVoxRelationReferences<T> property itself. That object is a read handle bound to the loaded entity and content scope. The handler records intent through changes.Relations, and Vox applies that intent in the same storage transaction as the entity body, relation links, inverse index, change event, history entry and recorded effects that the change processing handles afterwards. If validation, optimistic concurrency, or persistence fails, neither side is committed. The read handle does not cache pages, so a call made after the save queries the newly committed relation contents.

Index-backed relations use the same ownership attributes as fields. A declaration directly on the relation takes precedence over its containing object. Otherwise, ownership is inherited from that object, with local ownership as the default for an IVoxEntity and imported ownership for an IVoxExternalEntity. Neighbouring fields do not affect it, and a containing object can have only relations.

Use [VoxImportOwned(typeof(ProductCategoriesImport))] on a relation to assign it to that import, or leave out the types to allow every import of the entity type. Marker interfaces and base classes work as they do for fields. An import may own only relations, with no ordinary fields. [VoxOwned] makes a relation locally editable, including inside an imported object or on an external entity. [VoxSystemOwned] reserves it for Vox. Index-backed relations cannot be calculated.

For locally owned index-backed relations, Vox exposes Set{Property}, Add{Property}, and Remove{Property} default actions. Custom update actions must list the relation names they may change in [VoxUpdateRelations]; attempts to mutate another relation, or one that is imported or system-owned, are rejected. Cell writes also require local ownership. Imports may mutate only relations assigned to them. See Importing relations for a relation-only import example.

Index-backed relation mutations don't have versions of their own; inline a relation into the entity data when concurrent changes of it need optimistic concurrency.

Link and Unlink read and write only the links they name, so linking one product to a category with a million products is as cheap as linking it to one with none. Replace compares the existing links and the replacement as sets. A replacement of more links than a complete read of a relation gets (VoxReadBudgets.MaxRelationLinks, 10,000 by default), counting both the existing links and the new ones, is staged instead: the save commits the entity and the staged links, and Vox's vox_relation_replacement background work then removes and adds the links a page at a time, each page committed with its change events. The links converge to the replacement rather than changing at once: reads see the links as the replacement has got them, snapshots of the entity wait until it's done, and a Link or Unlink in the meantime is applied at once and kept by the replacement. Deleting an entity with more links than that removes them the same way. Unpublishing an entity, replacing its links in a draft or release, and making a draft's links its parent's again read every link in one save, so they're refused with an error that names the relation and the budget when it has more links than that: unlink them in batches first. Publishing the delete of such an entity from a release records only the first links up to the budget for the publication's history, so restoring that publication restores only those.

Index-backed relations are sets: Entity Framework storage orders their links by the entity type and id of the related entity and Redis by when they were linked, which batches page through, but neither is a position you can set. Use a reference list when the order matters. Every change of the links is published to both of their ends, see Changes of links.

The default action payload contains a references array:

  • SetCategories uses Replace.
  • AddCategories uses Link.
  • RemoveCategories uses Unlink.

Default relation actions require the normal edit permission scoped to the relation name, for example Product:Edit:categories. Initial mutations made by a handler for the default create action are authorized the same way; a custom create action continues to use its custom action permission.

Create handlers receive the same IVoxEntityChanges<TEntity> collector and may establish initial links. Import handlers receive a collector on every invocation; retries discard the mutations from the failed attempt and collect a fresh set against the latest entity version. Multiple imports for one entity in the same batch are applied in order, including their relation mutations.

Enums​

An enum is always its name, eg "Thema", never its number, without any attribute on the enum: in stored entities, drafts, history, events, imports, the API, subscriptions and projections, as values, in collections and as dictionary keys. Names are written in the case they're declared in and read ignoring case, so "thema" is read as Thema.

public enum ClassificationScheme { Thema, Sap, Varegruppe }

public class PrefixRule : IVoxEntity
{
[VoxFilterable]
public virtual ClassificationScheme Scheme { get; set; }
}
{ "id": "thema:YP", "scheme": "Thema", "prefix": "YP" }

A number, eg 0 or "0", or a list of names, eg "Thema, Sap", isn't a name, so a request with one is rejected with the names it can have. A value that isn't a member, eg (ClassificationScheme)7, can't be written and fails rather than being stored as a number. An enum doesn't need a member for zero, but then an entity whose property was never set holds a value that isn't a member, eg enum Priority { Low = 1, High = 2 } holds (Priority)0, and saving it fails until the property is set.

Since a value is one name, a model can't use an enum that has more than one name for a value: a [Flags] enum (use a list of the enum, eg List<Allergen>), aliases, eg Old = 1, New = 1, or names that differ only by case, eg Sap and SAP. The model fails when it's built. Because the names are what's stored, adding a member or reordering the members changes nothing stored, while renaming or removing one changes stored values, see Model evolution. See Querying and search for filtering and sorting enums.

Selectors​

A VoxSelector<T> property holds a rule that picks entities of T, which an editor builds in the admin instead of picking entities one by one, eg the products of a product list:

public class ProductList : IVoxEntity
{
public required virtual string Name { get; set; }

[Display(Description = "The products the list shows. Without a rule it shows none.")]
public virtual VoxSelector<Product>? Rule { get; set; }
}

A selector is one value: it's stored, sent and kept in history as the filter it holds, and a change of any condition is a change of the whole rule. Null means there's no rule. What the entity does without one is the model's choice, so say it in the property's description, eg "Without a rule it shows none".

Declare a selector on the entity or on an object in it. A selector can't be in a list, a dictionary or a varying value, and can't be marked [VoxFilterable] or [VoxSortable] itself. T is one registered entity type: for a family, select its base type and compare its kind to pick one kind. Neither the entity type that declares a selector nor T can be a transient entity type. The model fails when it's built otherwise, naming the property.

Use a selector when the set should follow the data, eg every Northpeak jacket in stock, and references when an editor picks the exact entities. See Querying and search for what a selector can say and how to run one.

Property names​

A property's name in JSON is its canonical name, which is what Vox stores and what every path, filter, sort, action payload, editor path, subscription and contract refers to it by: its [JsonPropertyName] exactly as written, or else its CLR name in camel case. The CLR name is only how C# accesses it.

public class Article : IVoxEntity
{
[JsonPropertyName("title")]
[VoxFilterable]
public virtual string? Name { get; set; }

[JsonPropertyName("editorial")]
public virtual ArticleContent Content { get; set; } = new();
}

public class ArticleContent
{
[JsonPropertyName("headline")]
public virtual string? Heading { get; set; }
}
{ "id": "a1", "title": "Rain jacket", "editorial": { "headline": "Light and waterproof" } }

The fields are title and editorial.headline, a filter is on title, and the default set actions are SetTitle and SetEditorial, whose generated commands are ArticleActions.SetName and ArticleActions.SetContent with members that serialize as title and editorial. Typed expressions, eg article => article.Name, are translated to the canonical paths. Renaming Name in C# while keeping [JsonPropertyName("title")] changes nothing stored, see Canonical names and CLR names.

A nested class is an object whose properties are fields, like ArticleContent, when it has a public parameterless constructor and is neither abstract nor has a JsonConverter. Otherwise it's one field holding the whole value, eg record Dimensions(decimal Width, decimal Height) makes the field dimensions, and [VoxUnique] or a VoxVarying property inside it fails at startup with an error that says why.

References in nested lists and dictionaries​

References can be anywhere in the value of an entity: in the objects of lists, as the keys and values of dictionaries and ordered dictionaries, and in lists of lists, as deep as they're nested. The values stay in the entity's JSON, and every reference in them is a relation that Vox indexes, so it can be read from both ends, filtered on and expanded. A retailer's model has them in many places:

// Order: its lines, the stores it's sourced from, in the order they're tried, with the most units each may ship, and
// its shipments, each from a store
public virtual List<OrderLine> Lines { get; set; } = [];
public virtual OrderedDictionary<VoxReference<Store>, int> SourcingPlan { get; set; } = [];
public virtual List<Shipment> Shipments { get; set; } = [];

// A line: the product, the units reserved in each store and the campaigns of its discounts
public class OrderLine
{
public virtual VoxReference<Product> Product { get; set; } = new();
public virtual int Quantity { get; set; }
public virtual Dictionary<VoxReference<Store>, int> Allocations { get; set; } = [];
public virtual List<OrderLineDiscount> Discounts { get; set; } = [];
}

public class OrderLineDiscount
{
public virtual VoxReference<Campaign>? Campaign { get; set; }
public virtual decimal Amount { get; set; }
}

public class Shipment
{
public virtual VoxReference<Store> ShipFrom { get; set; } = new();
public virtual string Carrier { get; set; } = "";
}

// Store: the product in each numbered display slot, eg a window or the end of an aisle
public virtual Dictionary<int, VoxReference<Product>> DisplaySlots { get; set; } = [];

// Campaign: a mix and match deal, a product from each group, and the price list of each market
public virtual List<List<VoxReference<Product>>> BundleGroups { get; set; } = [];

[VoxRelation(Path = "{key}", InverseName = "pricedCampaigns")]
[VoxRelation(Path = "{value}", InverseName = "campaigns")]
public virtual Dictionary<VoxReference<Market>, VoxReference<PriceList>> PriceLists { get; set; } = [];

Each place a reference can be is a relation of its own, with a path that names no particular line or key: [] is every item of a list, {key} and {value} the keys and values of a dictionary.

Entity typePathRelationKey
Orderlines[].productlinesProductOrder_Lines_Product
Orderlines[].allocations{key}linesAllocationsKeyOrder_Lines_Allocations_Key
Orderlines[].discounts[].campaignlinesDiscountsCampaignOrder_Lines_Discounts_Campaign
OrdersourcingPlan{key}sourcingPlanKeyOrder_SourcingPlan_Key
Ordershipments[].shipFromshipmentsShipFromOrder_Shipments_ShipFrom
StoredisplaySlots{value}displaySlotsValueStore_DisplaySlots_Value
CampaignpriceLists{key}priceListsKeyCampaign_PriceLists_Key
CampaignbundleGroups[][]bundleGroupsCampaign_BundleGroups

The keys and values of a dictionary are separate relations, also when both are to the same entity type. Relations of lists without dictionaries, eg shipments[].shipFrom, keep the names they always had. The inverse names default to the entity type and the same words, eg orderLinesDiscountsCampaign of the campaigns.

A relation through a list or a dictionary is to many, even when each shipment has one store. A store that three shipments are from is one link, which stays while any of them is and goes with the last one; the value keeps every shipment. Changing a quantity, or the order of the entries, changes no link.

[VoxRelation] on a property configures the only relation in its value. A property with references in more than one place, eg a dictionary whose keys and values are both references, has an attribute per relation, each selecting its relation with Path, eg "{key}"; one without a Path there is a model error, so one inverse name or access grant is never applied to several relations. [VoxInverseRelation] takes the same Path. It names the reference property, so it can't tell apart two relations of one entity type whose reference properties have the same name in different lists, eg Accessories[].Product and SpareParts[].Product of a bundle: give them different names, eg SparePart, to declare an inverse navigation of each.

A value with references can't contain itself, eg a tree of menu items with a product in each, since its references would be at endless paths: that's a model error rather than references that Vox silently doesn't find.

Reference keys​

A dictionary whose keys are references is stored as a JSON object keyed by the canonical Vox entity URIs of the entities, the same URIs that rich text refers to entities by:

{
"vox://entity/Store/sthlm-01": 2,
"vox://entity/Store/gbg-01": 1
}

The URI has the registered name of the entity type, also when the reference leaves it out because its target is one type, and the id escaped like Uri.EscapeDataString, so ids with /, ., %, spaces or Unicode are kept. Only the canonical spelling is read. A reference that's read back from a key has no entity type when its target is one type, so it equals the application's own references. VoxEntityUri creates and parses the URIs, and entityUris.ts in the client does the same with the same rules.

A dictionary never has two entries for one key: writing two keys that are the same entity, eg with and without its entity type, fails, and so does reading a JSON object with the same key twice, or with 1 and 01 as number keys. VoxReferenceComparer.For<VoxReference<Store>>(entityTypes) compares references the way Vox does, for an application's own dictionaries. A cached reference can't be a key, since a URI can't hold its cached values; it can be a value.

When an entity type is renamed with RenameEntityType, the URIs of the keys that refer to it are renamed too, eg vox://entity/Item/1 to vox://entity/Product/1, in place so that the entries keep their order, and so is the entity type of polymorphic references to it. Documents are renamed as they're read, and the model migration rewrites the stored ones like it does for renamed properties.

Ordered dictionaries​

An OrderedDictionary<TKey, TValue> is stored like a dictionary, with its entries in their order, which is part of its value: moving an entry is a change of the field, it's saved, it's in history, and it's synchronized. Reading the JSON gives an ordered dictionary with the entries in the same order. Changing a dictionary to an ordered one, or back, is a change of the field's type that needs a declaration, since one promises an order and the other doesn't.

Vox decides whether a value changed by comparing its JSON, so a dictionary whose entries are written in another order is changed too, although it promises no order. The admin UI never reorders the entries of a dictionary, so that only happens when an API caller or an import writes them in another order.

JavaScript moves the keys of a JSON object that look like integers ("36", "101", but not "036" or "EU 36") to the front, in number order, whatever order they were sent in. That goes for every key type: number keys, text keys such as shoe sizes, and reference keys whose ids look like integers, eg stores numbered 101 and 36. Such an ordered dictionary keeps its order in .NET and in storage, but every JavaScript client shows it in number order, the admin UI included, and an edit in the admin saves the number order over the intended one. When the order matters and differs from the number order, use a list of objects, which keeps any order everywhere, or keys that don't look like integers. Other keys keep their order everywhere.

Editing nested values​

A list or dictionary is one field, however deep its references are: drafts, imports, ownership and permissions treat Shipments or SourcingPlan as a whole, and an action that sets the field sets all of it. The relations in it are changed by changing the value, so they can't be linked or unlinked from the other end, which couldn't make up the line or key that a reference needs. The Relations tab of a store says so for the order lines its units are allocated to.

The admin UI edits a list or dictionary as a table with a row per item or entry: the key, eg a store picker for a reference key or a number, and as many of the fields of the value as fit, eg the store and carrier of a shipment. The rest of a value, eg a line's discounts, is edited below its row, or in a dialog of its own. The items of lists and the entries of ordered dictionaries are moved up and down, and rows inserted above or below others. A list of lists of references, eg the bundle groups of a campaign, has a row per group with its references in it, which are dragged within a group or into another one. A key that isn't valid, or is another row's, stays in its row with a message, and the value keeps the row's last valid key until it's fixed. The history of an entity compares lists by position, dictionaries by key and ordered dictionaries by key and position.

The API's metadata describes a dictionary as the type Dictionary, with key, item and isOrdered, and the items of lists and the keys and values of dictionaries recursively, with the entity types of their references. A relation has its valuePath, eg lines[].allocations{key}, also from the other end. titles takes the paths of relations, eg lines[].discounts[].campaign or lines[].allocations{key}; the titles of reference keys are in _keyTitles of the entity, by their URIs.

References that were stored in nested values before Vox looked into them, eg in a list of lists, are linked the next time their entity is written.

Inverse navigation properties​

Sometimes the inverse direction is useful in application code. Keep the reference on the entity that owns the relation, then declare a derived navigation on the other type with [VoxInverseRelation]:

public class Category : IVoxEntity
{
// The normal IVoxEntity properties are omitted.

[VoxRelation(Name = "parent", InverseName = "children")]
public virtual VoxReference<Category>? Parent { get; set; }

[VoxInverseRelation(nameof(Parent))]
public IVoxRelatedEntities<Category> Children { get; private set; } = null!;
}

var children = await category.Children.LoadAsync(cancellationToken);

Parent remains the only stored source of truth. Children is initialized by Vox when the category is materialized, loads on its first LoadAsync call, and keeps the result on that entity instance. In a read cache scope it reads the scope, and loads again after a write cleared the scope. It is excluded from stored and API JSON. The load returns the complete relation; it does not apply MaxExpandCount or silently truncate the collection.

Use IVoxRelatedEntity<TEntity> instead for a single inverse:

public class Image : IVoxAsset
{
[VoxInverseRelation(nameof(Brand.Logo))]
public IVoxRelatedEntity<Brand> LogoOf { get; private set; } = null!;
}

A single inverse makes the relation one-to-one from that endpoint. Vox enforces the uniqueness in relation storage, so two brands cannot refer to the same logo. LoadAsync returns null when there is no related entity.

Loading inverse collections one owner at a time can create N+1 database reads. For a collection of owners, include the relation in their query, eg store.Query().Include(category => category.Children), or preload it into a read cache scope for owners that were read before, see Typed queries and included relations. Each owner's Children.LoadAsync then reads the scope. IVoxRelationLoader.LoadAllAsync<TEntity, TRelated> loads the complete relation of many owners in one operation too. The ordinary IVoxRelationLoader.LoadAsync overload remains intended for bounded API expansion and applies the relation's expansion limit unless an explicit maximum is supplied; it reads the links of all of the owners in one query per batch.

The relations of a transient entity type, eg a cart, are read in the inverse direction only when they're declared with InverseIndexed = true, eg [VoxRelation(InverseName = "carts", InverseIndexed = true)] on the cart's customer. An inverse read of one without it, eg the carts of a market, fails rather than returning nothing, see Inverse relations are opt-in.

Ids of new entities​

Every entity has a string id, which references, routes and events use. When a new entity is created without one, null or empty, Vox generates a GUID in the format Guid.NewGuid().ToString("N"), and a given id is kept, whether or not it's a GUID. The id is assigned before the entity is initialized, validated, authorized and written, so validators, relations, history and events all see the final id, and the create returns it. The same rule applies to typed and JSON creates, drafts and releases, custom creates and uploaded assets. Creating an entity with an id that's taken is a version conflict, which never overwrites the entity, and an update can't change an id.

[VoxRequireId] on an entity class requires the id of a new entity instead, eg the code of a language or market, the key of a choice, or the key of an integrated system that always supplies it. A missing, null, empty or whitespace-only id then fails with a validation error at id, and nothing is written. The attribute is inherited by subclasses. An entity family declares it on its root, since its kinds share their ids, and a kind that declares it alone is an error, as is the attribute on a singleton, whose id Vox gives it, or on an external entity type, whose ids are its source's. The rule is about creates: adding or removing it doesn't change the ids of existing entities, and restores, publishing, synchronization and replays keep the ids they're given.

The admin UI reserves two names. It opens the create screen of an entity type at /{routeName}/new, so an entity, attribute or subscription whose id is new, eg an order status with that key, can be read and changed through the API but not opened in the admin. And it tells Vox's own entity types, eg content releases, by the prefix Vox, so an application entity type whose name starts with it, eg Voxel, is left out of rich text embeds, the entities that can be added to a release and subscriptions. Give application entity types names without that prefix.

Creating entities​

Entities read by Vox already have their lazy inverse properties initialized. For application-created entities, prefer IVoxEntityFactory:

var category = entityFactory.Create<Category>();
category.Id = "jackets";
category.Slug = new VoxVarying<IVoxLanguage, string> { ["en"] = "jackets" };

When the entity participates in Vox.Routing, this slug is one segment rather than a denormalized hierarchy path. The route projection reads parents and publishes the complete path; see Routing and redirects.

Create<TEntity>() requires a parameterless constructor. Initialize(entity) can prepare an instance made by another factory or mapper. Calling a constructor directly is still supported as an advanced use case, but runtime-backed properties remain null until the instance is passed to Initialize or reloaded through Vox.

Cached references​

A cached reference is a relation reference that stores a selected subset of the target entity's data. It is useful when the owner should remain cheap to read even when the target lives in another store. It is deliberately a storage-level denormalization, not an application-facing entity projection.

A type implementing IVoxCachedReference<TEntity> is both the relation identity and its cached data:

public record BrandReference : VoxReference<Brand>, IVoxCachedReference<Brand>
{
public BrandReference(string id) : base(id) { }

public string? Name { get; init; }
public string? LogoPath { get; init; }
public DateTime RefreshedAtUtc { get; set; }
}

public class Product : IVoxEntity
{
public required BrandReference Brand { get; set; }
}

var name = product.Brand.Name;

Vox serializes the referenced entity and deserializes that JSON into the reference type, so cached properties are selected by JSON name. Id and EntityType are caller-owned relation identity; every other property is engine-owned, and values supplied by actions or imports are ignored. Cached properties should be nullable or have useful defaults because the target may not exist yet.

References can be polymorphic. If Image and Video both implement IMedia, a List<VoxReference<IMedia>> accepts both registered entity types. VoxReference<Image> accepts only images, while VoxReference<IVoxAsset> accepts every registered asset entity type. Polymorphic references include their concrete entity type in addition to their ID.

Cached inverse navigation​

An inverse property can cache the same kind of reference instead of loading related entities on demand:

public record ProductSummary : VoxReference<Product>, IVoxCachedReference<Product>
{
public string? Sku { get; init; }
public decimal Price { get; init; }
public DateTime RefreshedAtUtc { get; set; }
}

public class Brand : IVoxEntity
{
[VoxInverseRelation(nameof(Product.Brand))]
public List<ProductSummary> Products { get; private set; } = [];
}

Vox derives Brand.Products from Product.Brand, persists the complete cached collection on the brand, and updates it when a product is linked, unlinked, changed, created, or deleted. There is no item cap. Choosing a cached inverse means accepting the storage and refresh cost of the complete collection; use a lazy inverse or paged relation API for relations that may grow too large.

Cached inverse properties are engine-owned calculated fields. They are read-only in generated actions and imports; callers change the forward references instead. A non-list cached reference declares a one-to-one inverse just like IVoxRelatedEntity<TEntity>.

The generic /api/entity-types metadata identifies a declared inverse with navigationProperty and navigationKind (LazySingle, LazyMany, CachedSingle, or CachedMany). Generic tooling can describe the model without knowing application entity classes.

Calculated relations​

A cached inverse is a reference that Vox derives from the other end of a relation. A reference in a [VoxCalculated] field is the opposite: a forward relation whose calculation decides its links, eg the image that lists a product, picked from the media of its variants. Its links are in the relation index like those of an owned reference, so it has an inverse relation, eg listedProducts on an image, can be loaded and queried from both ends, and can carry memberships. It's read-only from both ends, and its links follow the calculated value in drafts, releases and at contexts. The metadata marks both ends with isCalculated. See Calculations.

Refresh strategies​

Dependency-tracked refresh is the default. It is appropriate for catalog data where a referenced entity change should update every owner promptly. A refresh loads targets through the normal calculation context and records existing or missing targets as dependencies. All tracked cached references on one owner entity type are updated by one aggregate calculation, exposed as CachedReference in /api/calculations.

Operational entities such as carts can opt out of that dependency fan-out by putting a refresh strategy next to the cached property:

public class CartLine
{
[VoxCachedReferenceRefresh(
VoxCachedReferenceRefreshMode.OnLoad,
MaxAgeSeconds = 24 * 60 * 60)]
public required CartProductReference Product { get; set; }
}

Vox then checks RefreshedAtUtc whenever the cart is loaded and refreshes the product reference only after it has become stale. The refresh is merged into the stored cart without replacing relation identities changed concurrently. It reads the referenced product from its configured routed storage but does not register a dependency, so product changes do not cause work for dormant carts.

Use VoxCachedReferenceRefreshMode.Explicit when Vox should never decide automatically. Either strategy can still be forced for a complete entity or one owned object:

cart = await cachedReferenceRefresher.RefreshReferencesAsync(cart, cancellationToken);
cart.Lines[0] = await cachedReferenceRefresher.RefreshReferencesAsync(
cart.Lines[0], cancellationToken);

Refreshing a registered Vox entity persists and concurrency-merges its cached values. Refreshing an owned object such as a cart line only changes that object in memory.

Cached values are calculated values, so they follow the draft or release they're read in. When a brand is renamed in a draft, its products have the new name in the draft and the published one elsewhere, without a draft of their own.

For rules more specific than age, implement IVoxCachedReferenceRefreshPolicy<TReference> and place its type on the property. Policies are scoped and can use dependency injection:

[VoxCachedReferenceRefresh<CartProductRefreshPolicy>]
public required CartProductReference Product { get; set; }

The policy runs only during entity loading. It receives the root entity, the object containing the property, the current reference, its property path, and the captured UTC time. OnLoad and Explicit references do not appear as calculation entries unless the same entity type also contains tracked cached references.

Lazy inverse navigation is available inside calculations too. Vox binds it to the current evaluation context, so accessing it records the same entity and relation dependencies as context.LoadRelatedAsync. Prefer the context's explicit batch methods when a calculation processes several owners.

A link carries no data of its own: it only says that two entities are related. When a relation needs data, eg where a store shelves a product, model the link as an entity of its own with references to both sides:

public class StoreAssortment : IVoxExternalEntity
{
// Built-in properties ...

[VoxRelation(InverseName = "assortment")]
public required virtual VoxReference<Store> Store { get; set; }

[VoxRelation(InverseName = "stores")]
public required virtual VoxReference<Product> Product { get; set; }

public virtual string? ShelfLocation { get; set; }
}

It has the same rules as any other entity, so it can be imported, varied by context and extended as the model grows. The relation index holds no positions either: the order of an embedded list is the order in the entity, and links read from the index are ordered by the related entities.

Assets​

Assets use the same entity and relation model. Their metadata is an ordinary entity while their binary content is handled by a replaceable content store. See Assets and media.