Cratis Chronicle model-bound projections: Build child collections
Use ChildrenFrom in a Cratis Chronicle model-bound projection when one read model should contain independently updated items, such as an order and its lines. The collection mapping identifies which events reach the children, which item each event selects, and which parent instance contains it.
Basic Children
Section titled “Basic Children”Put ChildrenFrom on the collection property or record parameter. Here, the event’s ItemId identifies the line item to add:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;
[EventType]public record MbChildrenLineItemAdded( Guid ItemId, string ProductName, int Quantity, decimal Price);
public record MbChildrenOrder( [Key] Guid OrderId,
[ChildrenFrom<MbChildrenLineItemAdded>(key: nameof(MbChildrenLineItemAdded.ItemId))] IEnumerable<MbChildrenLineItem> Items);
public record MbChildrenLineItem( [Key] Guid Id, // Chronicle automatically discovers this as the key string ProductName, int Quantity, decimal Price);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class MbChildrenLineItemAdded( val itemId: String, val productName: String, val quantity: Int, val price: Double)
@ReadModel@FromEvent(MbChildrenLineItemAdded::class)data class MbChildrenOrder( @ChildrenFrom(MbChildrenLineItemAdded::class, key = "itemId", identifiedBy = "itemId") val items: List<MbChildrenLineItem> = emptyList())
data class MbChildrenLineItem( val itemId: String = "", // Chronicle automatically discovers this as the key, via identifiedBy val productName: String = "", val quantity: Int = 0, val price: Double = 0.0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.readModels.ReadModel;
import java.util.Collections;import java.util.List;
@EventTyperecord MbChildrenLineItemAdded( String itemId, String productName, int quantity, double price) {}
@ReadModel@FromEvent(eventType = MbChildrenLineItemAdded.class)class MbChildrenOrder { @ChildrenFrom(eventType = MbChildrenLineItemAdded.class, key = "itemId", identifiedBy = "itemId") public List<MbChildrenLineItem> items = Collections.emptyList();}
class MbChildrenLineItem { public String itemId = ""; // Chronicle automatically discovers this as the key, via identifiedBy public String productName = ""; public int quantity = 0; public double price = 0.0;}defmodule MyApp.Events.MbChildrenLineItemAdded do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-added"
defstruct [:line_item_id, :product_name, :quantity]end
defmodule MyApp.ReadModels.MbChildrenLineItem do defstruct line_item_id: nil, product_name: nil, quantity: 0end
defmodule MyApp.ReadModels.MbChildrenOrder do use Cratis.Chronicle.ReadModels.ReadModel, types: [lines: {:list, MyApp.ReadModels.MbChildrenLineItem}]
defstruct order_id: nil, lines: []
children :lines, from: MyApp.Events.MbChildrenLineItemAdded, identified_by: :line_item_id, key: :line_item_id, set: [ line_item_id: :line_item_id, product_name: :product_name, quantity: :quantity ]endimport { childrenFrom, eventType, Guid } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenLineItemAdded { itemId: Guid = Guid.empty; productName = ''; quantity = 0; price = 0;}
// The `id` property is automatically discovered as the child's keyexport class MbChildrenLineItem { id: Guid = Guid.empty; productName = ''; quantity = 0; price = 0;}
export class MbChildrenOrder { id: Guid = Guid.empty;
@childrenFrom(MbChildrenLineItemAdded, 'itemId') @field(Array, { genericArguments: [MbChildrenLineItem] }) items: MbChildrenLineItem[] = [];}The child’s [Key] member stores that identity. The .NET client discovers it, so this example does not need an explicit identifiedBy.
Parameters
Section titled “Parameters”key selects the child identity from the incoming event. It defaults to EventSourceId when no event property is specified.
identifiedBy names the member holding that identity on the child. If omitted, the .NET client looks for a property or record parameter marked [Key], then a property named Id ignoring case, then a property matching the event key name. If none is found, it falls back to EventSourceId.
parentKey selects the containing read model instance. If omitted, the .NET client first looks for an event property whose type matches the parent’s Id type, excluding the child key property. If none matches, it uses the event source id.
When several event properties match the parent’s Id type, the first in declaration order is used. Supply parentKey to remove that ambiguity, or when the parent identifier is not named Id. For example, use parentKey: nameof(LineItemAdded.OrderId) when OrderId in the event identifies the parent. An explicit value always takes precedence.
Composite child keys (.NET)
Section titled “Composite child keys (.NET)”Set CompositeKey instead of key when a child is identified by two or more event properties. Each event property path maps to the same path within the child’s key object. Use [Key], an Id property, or identifiedBy to select that object on the child.
[EventType]public record PullRequestRecorded(string Owner, string Repository, int Number, string Title);
[EventType]public record PullRequestRemoved(string Owner, string Repository, int Number);
public record PullRequestKey(string Owner, string Repository, int Number);
public record TrackedPullRequest([Key] PullRequestKey Id, string Title);
public record PullRequestDashboard( [Key] Guid Id, [ChildrenFrom<PullRequestRecorded>(CompositeKey = new[] { nameof(PullRequestRecorded.Owner), nameof(PullRequestRecorded.Repository), nameof(PullRequestRecorded.Number) })] [RemovedWith<PullRequestRemoved>(CompositeKey = new[] { nameof(PullRequestRemoved.Owner), nameof(PullRequestRemoved.Repository), nameof(PullRequestRemoved.Number) })] IEnumerable<TrackedPullRequest> PullRequests);Within a parent, an event with the same values for all key parts updates the same child. If any part differs, it identifies a different child. To update a child from a later event, add another ChildrenFrom. To remove it, use RemovedWith. List the same paths in the same order in every declaration for the collection. RemovedWith supports composite keys for read model projections, not graph nodes.
Parent routing is separate from child identity. ChildrenFrom excludes the composite parts when inferring parentKey; RemovedWith defaults to the event source id unless you pass parentKey explicitly.
Auto-Mapping
Section titled “Auto-Mapping”By default, matching event properties map to child properties without explicit set mappings, as they do with FromEvent:
[EventType]public record MbChildrenAutoMapLineItemAdded( Guid ItemId, string ProductName, int Quantity, decimal Price);
public record MbChildrenAutoMapOrder( [Key] Guid OrderId,
[ChildrenFrom<MbChildrenAutoMapLineItemAdded>(key: nameof(MbChildrenAutoMapLineItemAdded.ItemId))] IEnumerable<MbChildrenAutoMapLineItem> Items);
public record MbChildrenAutoMapLineItem( [Key] Guid Id, string ProductName, // Automatically mapped from MbChildrenAutoMapLineItemAdded.ProductName int Quantity, // Automatically mapped from MbChildrenAutoMapLineItemAdded.Quantity decimal Price); // Automatically mapped from MbChildrenAutoMapLineItemAdded.Priceimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class MbChildrenAutoMapLineItemAdded( val itemId: String, val productName: String, val quantity: Int, val price: Double)
@ReadModel@FromEvent(MbChildrenAutoMapLineItemAdded::class)data class MbChildrenAutoMapOrder( @ChildrenFrom(MbChildrenAutoMapLineItemAdded::class, key = "itemId", identifiedBy = "itemId") val items: List<MbChildrenAutoMapLineItem> = emptyList())
data class MbChildrenAutoMapLineItem( val itemId: String = "", val productName: String = "", // Automatically mapped from MbChildrenAutoMapLineItemAdded.productName val quantity: Int = 0, // Automatically mapped from MbChildrenAutoMapLineItemAdded.quantity val price: Double = 0.0 // Automatically mapped from MbChildrenAutoMapLineItemAdded.price)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.readModels.ReadModel;
import java.util.Collections;import java.util.List;
@EventTyperecord MbChildrenAutoMapLineItemAdded( String itemId, String productName, int quantity, double price) {}
@ReadModel@FromEvent(eventType = MbChildrenAutoMapLineItemAdded.class)class MbChildrenAutoMapOrder { @ChildrenFrom(eventType = MbChildrenAutoMapLineItemAdded.class, key = "itemId", identifiedBy = "itemId") public List<MbChildrenAutoMapLineItem> items = Collections.emptyList();}
class MbChildrenAutoMapLineItem { public String itemId = ""; public String productName = ""; // Automatically mapped from MbChildrenAutoMapLineItemAdded.productName public int quantity = 0; // Automatically mapped from MbChildrenAutoMapLineItemAdded.quantity public double price = 0.0; // Automatically mapped from MbChildrenAutoMapLineItemAdded.price}Elixir does not support this workflow yet.import { eventType } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenAutoMapLineItemAdded { itemId: Guid = Guid.empty; productName = ''; quantity = 0; price = 0;}
export class MbChildrenAutoMapLineItem { id: Guid = Guid.empty; productName = ''; // Automatically mapped from MbChildrenAutoMapLineItemAdded.productName quantity = 0; // Automatically mapped from MbChildrenAutoMapLineItemAdded.quantity price = 0; // Automatically mapped from MbChildrenAutoMapLineItemAdded.price}
export class MbChildrenAutoMapOrder { id: Guid = Guid.empty;
@childrenFrom(MbChildrenAutoMapLineItemAdded, 'itemId') @field(Array, { genericArguments: [MbChildrenAutoMapLineItem] }) items: MbChildrenAutoMapLineItem[] = [];}Apply [NoAutoMap] to the child type in .NET when only explicit property mappings should run:
using Cratis.Chronicle.Projections;
[EventType]public record MbChildrenNoAutoMapLineItemAdded( Guid ItemId, string ProductName, int Quantity, decimal Price);
public record MbChildrenNoAutoMapOrder( [Key] Guid OrderId,
[ChildrenFrom<MbChildrenNoAutoMapLineItemAdded>(key: nameof(MbChildrenNoAutoMapLineItemAdded.ItemId))] IEnumerable<MbChildrenNoAutoMapLineItem> Items);
[NoAutoMap]public record MbChildrenNoAutoMapLineItem( [Key] Guid Id,
// Now you must use SetFrom for each property [SetFrom<MbChildrenNoAutoMapLineItemAdded>(nameof(MbChildrenNoAutoMapLineItemAdded.ProductName))] string ProductName,
[SetFrom<MbChildrenNoAutoMapLineItemAdded>(nameof(MbChildrenNoAutoMapLineItemAdded.Quantity))] int Quantity,
[SetFrom<MbChildrenNoAutoMapLineItemAdded>(nameof(MbChildrenNoAutoMapLineItemAdded.Price))] decimal Price);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.NoAutoMapimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class MbChildrenNoAutoMapOrderPlaced(val orderId: String)
@EventTypedata class MbChildrenNoAutoMapLineItemAdded( val itemId: String, val productName: String, val quantity: Int, val price: Double)
@ReadModel@FromEvent(MbChildrenNoAutoMapOrderPlaced::class)data class MbChildrenNoAutoMapOrder( @ChildrenFrom(MbChildrenNoAutoMapLineItemAdded::class, key = "itemId") val items: List<MbChildrenNoAutoMapLineItem> = emptyList())
// Now you must use @SetFrom for each property@NoAutoMapdata class MbChildrenNoAutoMapLineItem( @SetFrom("productName", MbChildrenNoAutoMapLineItemAdded::class) val productName: String = "",
@SetFrom("quantity", MbChildrenNoAutoMapLineItemAdded::class) val quantity: Int = 0,
@SetFrom("price", MbChildrenNoAutoMapLineItemAdded::class) val price: Double = 0.0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.NoAutoMap;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
import java.util.List;
@EventTyperecord MbChildrenNoAutoMapOrderPlaced(String orderId) {}
@EventTyperecord MbChildrenNoAutoMapLineItemAdded( String itemId, String productName, int quantity, double price) {}
@ReadModel@FromEvent(eventType = MbChildrenNoAutoMapOrderPlaced.class)record MbChildrenNoAutoMapOrder( @ChildrenFrom(eventType = MbChildrenNoAutoMapLineItemAdded.class, key = "itemId") List<MbChildrenNoAutoMapLineItem> items) {}
// Now you must use @SetFrom for each property@NoAutoMaprecord MbChildrenNoAutoMapLineItem( @SetFrom(propertyPath = "productName", eventType = MbChildrenNoAutoMapLineItemAdded.class) String productName,
@SetFrom(propertyPath = "quantity", eventType = MbChildrenNoAutoMapLineItemAdded.class) int quantity,
@SetFrom(propertyPath = "price", eventType = MbChildrenNoAutoMapLineItemAdded.class) double price) {}Elixir does not support this workflow yet.import { childrenFrom, eventType, Guid, noAutoMap, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenNoAutoMapLineItemAdded { itemId: Guid = Guid.empty; productName = ''; quantity = 0; price = 0;}
@noAutoMapexport class MbChildrenNoAutoMapLineItem { id: Guid = Guid.empty;
// With AutoMap disabled, explicitly map each property you want to populate. @setFrom(MbChildrenNoAutoMapLineItemAdded, 'productName') productName = '';
@setFrom(MbChildrenNoAutoMapLineItemAdded, 'quantity') quantity = 0;
@setFrom(MbChildrenNoAutoMapLineItemAdded, 'price') price = 0;}
export class MbChildrenNoAutoMapOrder { id: Guid = Guid.empty;
@childrenFrom(MbChildrenNoAutoMapLineItemAdded, 'itemId') @field(Array, { genericArguments: [MbChildrenNoAutoMapLineItem] }) items: MbChildrenNoAutoMapLineItem[] = [];}Recursive Attribute Processing
Section titled “Recursive Attribute Processing”A child can maintain its own values instead of only copying the event that created it. Put property mappings and counter attributes on the child type:
[EventType]public record MbChildrenCountersItemAddedToCart(Guid ItemId, string ProductName, decimal Price, int InitialQuantity);
[EventType]public record MbChildrenCountersQuantityIncreased(Guid ItemId);
[EventType]public record MbChildrenCountersQuantityDecreased(Guid ItemId);
public record MbChildrenCountersShoppingCart( [Key] Guid CartId,
[ChildrenFrom<MbChildrenCountersItemAddedToCart>( key: nameof(MbChildrenCountersItemAddedToCart.ItemId))] IEnumerable<MbChildrenCountersCartItem> Items);
// Child type with its own projection attributespublic record MbChildrenCountersCartItem( [Key] Guid Id,
[SetFrom<MbChildrenCountersItemAddedToCart>(nameof(MbChildrenCountersItemAddedToCart.ProductName))] string ProductName,
[SetFrom<MbChildrenCountersItemAddedToCart>(nameof(MbChildrenCountersItemAddedToCart.Price))] decimal Price,
[SetFrom<MbChildrenCountersItemAddedToCart>(nameof(MbChildrenCountersItemAddedToCart.InitialQuantity))] [Increment<MbChildrenCountersQuantityIncreased>] [Decrement<MbChildrenCountersQuantityDecreased>] int Quantity);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.Decrementimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.Incrementimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class MbChildrenCountersItemAddedToCart( val itemId: String, val productName: String, val price: Double, val initialQuantity: Int)
@EventTypedata class MbChildrenCountersQuantityIncreased(val itemId: String)
@EventTypedata class MbChildrenCountersQuantityDecreased(val itemId: String)
@ReadModel@FromEvent(MbChildrenCountersItemAddedToCart::class)data class MbChildrenCountersShoppingCart( @ChildrenFrom(MbChildrenCountersItemAddedToCart::class, key = "itemId", identifiedBy = "itemId") @ChildrenFrom(MbChildrenCountersQuantityIncreased::class, key = "itemId", identifiedBy = "itemId") @ChildrenFrom(MbChildrenCountersQuantityDecreased::class, key = "itemId", identifiedBy = "itemId") val items: List<MbChildrenCountersCartItem> = emptyList())
// Child type with its own projection attributesdata class MbChildrenCountersCartItem( val itemId: String = "",
@SetFrom("productName", MbChildrenCountersItemAddedToCart::class) val productName: String = "",
@SetFrom("price", MbChildrenCountersItemAddedToCart::class) val price: Double = 0.0,
@SetFrom("initialQuantity", MbChildrenCountersItemAddedToCart::class) @Increment(MbChildrenCountersQuantityIncreased::class) @Decrement(MbChildrenCountersQuantityDecreased::class) val quantity: Int = 0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.Decrement;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.Increment;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
import java.util.Collections;import java.util.List;
@EventTyperecord MbChildrenCountersItemAddedToCart( String itemId, String productName, double price, int initialQuantity) {}
@EventTyperecord MbChildrenCountersQuantityIncreased(String itemId) {}
@EventTyperecord MbChildrenCountersQuantityDecreased(String itemId) {}
@ReadModel@FromEvent(eventType = MbChildrenCountersItemAddedToCart.class)class MbChildrenCountersShoppingCart { @ChildrenFrom(eventType = MbChildrenCountersItemAddedToCart.class, key = "itemId", identifiedBy = "itemId") @ChildrenFrom(eventType = MbChildrenCountersQuantityIncreased.class, key = "itemId", identifiedBy = "itemId") @ChildrenFrom(eventType = MbChildrenCountersQuantityDecreased.class, key = "itemId", identifiedBy = "itemId") public List<MbChildrenCountersCartItem> items = Collections.emptyList();}
// Child type with its own projection attributesclass MbChildrenCountersCartItem { public String itemId = "";
@SetFrom(propertyPath = "productName", eventType = MbChildrenCountersItemAddedToCart.class) public String productName = "";
@SetFrom(propertyPath = "price", eventType = MbChildrenCountersItemAddedToCart.class) public double price = 0.0;
@SetFrom(propertyPath = "initialQuantity", eventType = MbChildrenCountersItemAddedToCart.class) @Increment(eventType = MbChildrenCountersQuantityIncreased.class) @Decrement(eventType = MbChildrenCountersQuantityDecreased.class) public int quantity = 0;}defmodule MyApp.Events.MbChildrenItemAddedToCart do use Cratis.Chronicle.Events.EventType, id: "mb-children-item-added-to-cart"
defstruct [:cart_item_id, :product_name, :quantity]end
defmodule MyApp.Events.MbChildrenQuantityIncreased do use Cratis.Chronicle.Events.EventType, id: "mb-children-quantity-increased"
defstruct [:cart_item_id, :amount]end
defmodule MyApp.ReadModels.MbChildrenCartItem do defstruct cart_item_id: nil, product_name: nil, quantity: 0end
defmodule MyApp.ReadModels.MbChildrenCart do use Cratis.Chronicle.ReadModels.ReadModel, types: [items: {:list, MyApp.ReadModels.MbChildrenCartItem}]
defstruct cart_id: nil, items: []
children :items, identified_by: :cart_item_id do from MyApp.Events.MbChildrenItemAddedToCart, key: :cart_item_id, set: [ cart_item_id: :cart_item_id, product_name: :product_name, quantity: :quantity ]
from MyApp.Events.MbChildrenQuantityIncreased, key: :cart_item_id, add: [quantity: :amount] endendimport { childrenFrom, decrement, eventType, Guid, increment, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenCountersItemAddedToCart { itemId: Guid = Guid.empty; productName = ''; price = 0; initialQuantity = 0;}
@eventType()export class MbChildrenCountersQuantityIncreased { itemId: Guid = Guid.empty;}
@eventType()export class MbChildrenCountersQuantityDecreased { itemId: Guid = Guid.empty;}
// Child type with its own projection decoratorsexport class MbChildrenCountersCartItem { id: Guid = Guid.empty;
@setFrom(MbChildrenCountersItemAddedToCart, 'productName') productName = '';
@setFrom(MbChildrenCountersItemAddedToCart, 'price') price = 0;
@setFrom(MbChildrenCountersItemAddedToCart, 'initialQuantity') @increment(MbChildrenCountersQuantityIncreased) @decrement(MbChildrenCountersQuantityDecreased) quantity = 0;}
export class MbChildrenCountersShoppingCart { id: Guid = Guid.empty;
@childrenFrom(MbChildrenCountersItemAddedToCart, 'itemId') @field(Array, { genericArguments: [MbChildrenCountersCartItem] }) items: MbChildrenCountersCartItem[] = [];}The add event supplies the product name, price, and initial quantity. Later quantity events use the child’s increment and decrement mappings to change the selected item’s quantity by one. These mappings are built from the child’s attributes; you do not repeat them on the parent.
Class-Level FromEvent on Child Types
Section titled “Class-Level FromEvent on Child Types”Put FromEvent on the child type when another event should update matching child properties by convention. That subscription belongs to the child collection, not the root model. Use parentKey when the update event carries the parent id separately:
[EventType]public record MbChildrenChildFromEventConfigurationAdded(Guid DashboardId, Guid ConfigurationId, string Name);
[EventType]public record MbChildrenChildFromEventConfigurationRenamed(Guid DashboardId, Guid Id, string Name);
public record MbChildrenChildFromEventDashboard( [Key] Guid Id, string Name,
[ChildrenFrom<MbChildrenChildFromEventConfigurationAdded>( key: nameof(MbChildrenChildFromEventConfigurationAdded.ConfigurationId), parentKey: nameof(MbChildrenChildFromEventConfigurationAdded.DashboardId))] IEnumerable<MbChildrenChildFromEventConfiguration> Configurations);
[FromEvent<MbChildrenChildFromEventConfigurationRenamed>(parentKey: nameof(MbChildrenChildFromEventConfigurationRenamed.DashboardId))]public record MbChildrenChildFromEventConfiguration( [Key] Guid Id, string Name);Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.MbChildrenChildFromEventConfigurationAdded do use Cratis.Chronicle.Events.EventType, id: "mb-children-child-from-event-configuration-added"
defstruct [:dashboard_id, :configuration_id, :name]end
defmodule MyApp.Events.MbChildrenChildFromEventConfigurationRenamed do use Cratis.Chronicle.Events.EventType, id: "mb-children-child-from-event-configuration-renamed"
defstruct [:dashboard_id, :id, :name]end
defmodule MyApp.ReadModels.MbChildrenChildFromEventConfiguration do defstruct id: nil, name: nilend
defmodule MyApp.ReadModels.MbChildrenChildFromEventDashboard do use Cratis.Chronicle.ReadModels.ReadModel, types: [configurations: {:list, MyApp.ReadModels.MbChildrenChildFromEventConfiguration}]
defstruct id: nil, name: nil, configurations: []
children :configurations, identified_by: :id do from MyApp.Events.MbChildrenChildFromEventConfigurationAdded, key: :configuration_id, parent_key: :dashboard_id, set: [id: :configuration_id, name: :name]
# The child is also updated by an event that carries the id of the child itself and the # dashboard it belongs to. from MyApp.Events.MbChildrenChildFromEventConfigurationRenamed, key: :id, parent_key: :dashboard_id, set: [name: :name] endendimport { childrenFrom, eventType, fromEvent, Guid } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenChildFromEventConfigurationAdded { dashboardId: Guid = Guid.empty; configurationId: Guid = Guid.empty; name = '';}
@eventType()export class MbChildrenChildFromEventConfigurationRenamed { dashboardId: Guid = Guid.empty; id: Guid = Guid.empty; name = '';}
@fromEvent(MbChildrenChildFromEventConfigurationRenamed, { parentKey: 'dashboardId' })export class MbChildrenChildFromEventConfiguration { id: Guid = Guid.empty; name = '';}
export class MbChildrenChildFromEventDashboard { id: Guid = Guid.empty; name = '';
@childrenFrom(MbChildrenChildFromEventConfigurationAdded, 'configurationId', undefined, 'dashboardId') @field(Array, { genericArguments: [MbChildrenChildFromEventConfiguration] }) configurations: MbChildrenChildFromEventConfiguration[] = [];}ChildrenFrom adds the configuration. The child’s FromEvent routes later rename events to it under the dashboard selected by DashboardId; the rename updates the configuration’s Name, not the dashboard’s. parentKey corresponds to .UsingParentKey(...) in a fluent child projection, while [Key] makes identifiedBy unnecessary here.
Removing Children
Section titled “Removing Children”Use RemovedWith to remove a selected child without deleting its parent. Declare it either on the collection or on the child type:
Property-Level Removal
Section titled “Property-Level Removal”Put the rule beside ChildrenFrom when the parent should own the collection’s removal behavior:
[EventType]public record MbChildrenRemovalPropertyLineItemAdded(Guid ItemId, string Description);
[EventType]public record MbChildrenRemovalPropertyLineItemRemoved(Guid ItemId);
public record MbChildrenRemovalPropertyOrder( [Key] Guid Id,
[ChildrenFrom<MbChildrenRemovalPropertyLineItemAdded>(key: nameof(MbChildrenRemovalPropertyLineItemAdded.ItemId))] [RemovedWith<MbChildrenRemovalPropertyLineItemRemoved>(key: nameof(MbChildrenRemovalPropertyLineItemRemoved.ItemId))] IEnumerable<MbChildrenRemovalPropertyOrderLine> Lines);
public record MbChildrenRemovalPropertyOrderLine( [Key] Guid Id, string Description);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.RemovedWithimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class MbChildrenRemovalPropertyLineItemAdded(val itemId: String, val description: String)
@EventTypedata class MbChildrenRemovalPropertyLineItemRemoved(val itemId: String)
@ReadModel@FromEvent(MbChildrenRemovalPropertyLineItemAdded::class)data class MbChildrenRemovalPropertyOrder( @ChildrenFrom(MbChildrenRemovalPropertyLineItemAdded::class, key = "itemId", identifiedBy = "itemId") @RemovedWith(MbChildrenRemovalPropertyLineItemRemoved::class, key = "itemId") val lines: List<MbChildrenRemovalPropertyOrderLine> = emptyList())
data class MbChildrenRemovalPropertyOrderLine( val itemId: String = "",
@SetFrom("description", MbChildrenRemovalPropertyLineItemAdded::class) val description: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.RemovedWith;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
import java.util.Collections;import java.util.List;
@EventTyperecord MbChildrenRemovalPropertyLineItemAdded(String itemId, String description) {}
@EventTyperecord MbChildrenRemovalPropertyLineItemRemoved(String itemId) {}
@ReadModel@FromEvent(eventType = MbChildrenRemovalPropertyLineItemAdded.class)class MbChildrenRemovalPropertyOrder { @ChildrenFrom(eventType = MbChildrenRemovalPropertyLineItemAdded.class, key = "itemId", identifiedBy = "itemId") @RemovedWith(eventType = MbChildrenRemovalPropertyLineItemRemoved.class, key = "itemId") public List<MbChildrenRemovalPropertyOrderLine> lines = Collections.emptyList();}
class MbChildrenRemovalPropertyOrderLine { public String itemId = "";
@SetFrom(propertyPath = "description", eventType = MbChildrenRemovalPropertyLineItemAdded.class) public String description = "";}defmodule MyApp.Events.MbChildrenLineItemAddedForRemoval do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-added-for-removal"
defstruct [:line_item_id, :product_name]end
defmodule MyApp.Events.MbChildrenLineItemRemoved do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-removed"
defstruct [:line_item_id]end
defmodule MyApp.ReadModels.MbChildrenRemovableLine do defstruct line_item_id: nil, product_name: nilend
defmodule MyApp.ReadModels.MbChildrenOrderWithRemoval do use Cratis.Chronicle.ReadModels.ReadModel, types: [lines: {:list, MyApp.ReadModels.MbChildrenRemovableLine}]
defstruct order_id: nil, lines: []
children :lines, identified_by: :line_item_id do from MyApp.Events.MbChildrenLineItemAddedForRemoval, key: :line_item_id, set: [line_item_id: :line_item_id, product_name: :product_name]
removed_with MyApp.Events.MbChildrenLineItemRemoved, key: :line_item_id endendimport { childrenFrom, eventType, Guid, removedWith } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenRemovalPropertyLineItemAdded { itemId: Guid = Guid.empty; description = '';}
@eventType()export class MbChildrenRemovalPropertyLineItemRemoved { itemId: Guid = Guid.empty;}
export class MbChildrenRemovalPropertyOrderLine { id: Guid = Guid.empty; description = '';}
export class MbChildrenRemovalPropertyOrder { id: Guid = Guid.empty;
@childrenFrom(MbChildrenRemovalPropertyLineItemAdded, 'itemId') @removedWith(MbChildrenRemovalPropertyLineItemRemoved, 'itemId') @field(Array, { genericArguments: [MbChildrenRemovalPropertyOrderLine] }) lines: MbChildrenRemovalPropertyOrderLine[] = [];}Class-Level Removal
Section titled “Class-Level Removal”Put RemovedWith on the child type when the removal rule belongs with that type:
[EventType]public record MbChildrenRemovalClassLineItemAdded(Guid ItemId, string Description);
[EventType]public record MbChildrenRemovalClassLineItemRemoved(Guid OrderId, Guid ItemId);
public record MbChildrenRemovalClassOrder( [Key] Guid Id,
[ChildrenFrom<MbChildrenRemovalClassLineItemAdded>(key: nameof(MbChildrenRemovalClassLineItemAdded.ItemId))] IEnumerable<MbChildrenRemovalClassOrderLine> Lines);
[RemovedWith<MbChildrenRemovalClassLineItemRemoved>( key: nameof(MbChildrenRemovalClassLineItemRemoved.ItemId), parentKey: nameof(MbChildrenRemovalClassLineItemRemoved.OrderId))]public record MbChildrenRemovalClassOrderLine( [Key] Guid Id, string Description);Kotlin does not support this workflow yet.Java does not support this workflow yet.# Elixir has no separate child-type module to carry a class-level removal attribute — a child's# `removed_with` always lives inside the owning `children` block, so this is the same declaration# as the property-level form.defmodule MyApp.Events.MbChildrenLineItemAddedForClassRemoval do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-added-for-class-removal"
defstruct [:line_item_id, :product_name]end
defmodule MyApp.Events.MbChildrenLineItemRemovedClassLevel do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-removed-class-level"
defstruct [:line_item_id]end
defmodule MyApp.ReadModels.MbChildrenRemovableLineClassLevel do defstruct line_item_id: nil, product_name: nilend
defmodule MyApp.ReadModels.MbChildrenOrderWithClassLevelRemoval do use Cratis.Chronicle.ReadModels.ReadModel, types: [lines: {:list, MyApp.ReadModels.MbChildrenRemovableLineClassLevel}]
defstruct order_id: nil, lines: []
children :lines, identified_by: :line_item_id do from MyApp.Events.MbChildrenLineItemAddedForClassRemoval, key: :line_item_id, set: [line_item_id: :line_item_id, product_name: :product_name]
removed_with MyApp.Events.MbChildrenLineItemRemovedClassLevel, key: :line_item_id endendimport { childrenFrom, eventType, Guid, removedWith } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenRemovalClassLineItemAdded { itemId: Guid = Guid.empty; description = '';}
@eventType()export class MbChildrenRemovalClassLineItemRemoved { orderId: Guid = Guid.empty; itemId: Guid = Guid.empty;}
@removedWith(MbChildrenRemovalClassLineItemRemoved, 'itemId', 'orderId')export class MbChildrenRemovalClassOrderLine { id: Guid = Guid.empty; description = '';}
export class MbChildrenRemovalClassOrder { id: Guid = Guid.empty;
@childrenFrom(MbChildrenRemovalClassLineItemAdded, 'itemId') @field(Array, { genericArguments: [MbChildrenRemovalClassOrderLine] }) lines: MbChildrenRemovalClassOrderLine[] = [];}RemovedWithJoin
Section titled “RemovedWithJoin”Use RemovedWithJoin when removal follows an event from a related entity’s stream. It can be declared on the collection or on the child type:
[EventType]public record MbChildrenRemovedFeatureActivated(Guid FeatureId, string Name);
[EventType]public record MbChildrenRemovedFeatureDeactivated(Guid FeatureId);
public record MbChildrenRemovedSubscription( [Key] Guid SubscriptionId,
[ChildrenFrom<MbChildrenRemovedFeatureActivated>(key: nameof(MbChildrenRemovedFeatureActivated.FeatureId))] [RemovedWithJoin<MbChildrenRemovedFeatureDeactivated>(key: nameof(MbChildrenRemovedFeatureDeactivated.FeatureId))] IEnumerable<MbChildrenRemovedFeature> Features);
public record MbChildrenRemovedFeature( [Key] Guid FeatureId, string Name);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.RemovedWithJoinimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class MbChildrenRemovedFeatureActivated(val featureId: String, val name: String)
@EventTypedata class MbChildrenRemovedFeatureDeactivated(val featureId: String)
@ReadModel@FromEvent(MbChildrenRemovedFeatureActivated::class)data class MbChildrenRemovedSubscription( @ChildrenFrom(MbChildrenRemovedFeatureActivated::class, key = "featureId", identifiedBy = "featureId") @RemovedWithJoin(MbChildrenRemovedFeatureDeactivated::class, key = "featureId") val features: List<MbChildrenRemovedFeature> = emptyList())
data class MbChildrenRemovedFeature( val featureId: String = "",
@SetFrom("name", MbChildrenRemovedFeatureActivated::class) val name: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.RemovedWithJoin;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
import java.util.Collections;import java.util.List;
@EventTyperecord MbChildrenRemovedFeatureActivated(String featureId, String name) {}
@EventTyperecord MbChildrenRemovedFeatureDeactivated(String featureId) {}
@ReadModel@FromEvent(eventType = MbChildrenRemovedFeatureActivated.class)class MbChildrenRemovedSubscription { @ChildrenFrom(eventType = MbChildrenRemovedFeatureActivated.class, key = "featureId", identifiedBy = "featureId") @RemovedWithJoin(eventType = MbChildrenRemovedFeatureDeactivated.class, key = "featureId") public List<MbChildrenRemovedFeature> features = Collections.emptyList();}
class MbChildrenRemovedFeature { public String featureId = "";
@SetFrom(propertyPath = "name", eventType = MbChildrenRemovedFeatureActivated.class) public String name = "";}defmodule MyApp.Events.MbChildrenGroupMemberAdded do use Cratis.Chronicle.Events.EventType, id: "mb-children-group-member-added"
defstruct [:member_id, :member_name]end
defmodule MyApp.Events.MbChildrenMemberDeletedElsewhere do use Cratis.Chronicle.Events.EventType, id: "mb-children-member-deleted-elsewhere"
defstruct [:member_id]end
defmodule MyApp.ReadModels.MbChildrenGroupMember do defstruct member_id: nil, member_name: nilend
defmodule MyApp.ReadModels.MbChildrenGroupWithJoinRemoval do use Cratis.Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.MbChildrenGroupMember}]
defstruct group_id: nil, members: []
children :members, identified_by: :member_id do from MyApp.Events.MbChildrenGroupMemberAdded, key: :member_id, set: [member_id: :member_id, member_name: :member_name]
# removed_with_join matches by a property on an event from a different stream, rather than # by the child's own key — the event never has to come from the group's own event source. removed_with_join MyApp.Events.MbChildrenMemberDeletedElsewhere, key: :member_id endendimport { childrenFrom, eventType, Guid, removedWithJoin } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbChildrenRemovedFeatureActivated { featureId: Guid = Guid.empty; name = '';}
@eventType()export class MbChildrenRemovedFeatureDeactivated { featureId: Guid = Guid.empty;}
export class MbChildrenRemovedFeature { featureId: Guid = Guid.empty; name = '';}
export class MbChildrenRemovedSubscription { id: Guid = Guid.empty;
@childrenFrom(MbChildrenRemovedFeatureActivated, 'featureId', 'featureId') @removedWithJoin(MbChildrenRemovedFeatureDeactivated, 'featureId') @field(Array, { genericArguments: [MbChildrenRemovedFeature] }) features: MbChildrenRemovedFeature[] = [];}For removal keys and deleting whole read model instances, see Removal.
Complete Example
Section titled “Complete Example”This order read model combines adding lines, changing their quantities, and removing them. Each operation selects a line by its item identity:
// Events[EventType]public record MbChildrenFullOrderCreated(string CustomerName);
[EventType]public record MbChildrenFullLineItemAdded( Guid ItemId, string ProductName, int InitialQuantity, decimal UnitPrice);
[EventType]public record MbChildrenFullQuantityAdjusted(Guid ItemId, int NewQuantity);
[EventType]public record MbChildrenFullLineItemRemoved(Guid ItemId);
// Read Modelspublic record MbChildrenFullOrder( [Key] Guid Id,
[SetFrom<MbChildrenFullOrderCreated>(nameof(MbChildrenFullOrderCreated.CustomerName))] string Customer,
[ChildrenFrom<MbChildrenFullLineItemAdded>(key: nameof(MbChildrenFullLineItemAdded.ItemId))] [RemovedWith<MbChildrenFullLineItemRemoved>(key: nameof(MbChildrenFullLineItemRemoved.ItemId))] IEnumerable<MbChildrenFullOrderLine> Lines);
[FromEvent<MbChildrenFullQuantityAdjusted>(key: nameof(MbChildrenFullQuantityAdjusted.ItemId))]public record MbChildrenFullOrderLine( [Key] Guid Id,
[SetFrom<MbChildrenFullLineItemAdded>(nameof(MbChildrenFullLineItemAdded.ProductName))] string Product,
[SetFrom<MbChildrenFullLineItemAdded>(nameof(MbChildrenFullLineItemAdded.InitialQuantity))] [SetFrom<MbChildrenFullQuantityAdjusted>(nameof(MbChildrenFullQuantityAdjusted.NewQuantity))] int Quantity,
[SetFrom<MbChildrenFullLineItemAdded>(nameof(MbChildrenFullLineItemAdded.UnitPrice))] decimal UnitPrice);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.ChildrenFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.RemovedWithimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
// Events@EventTypedata class MbChildrenFullOrderCreated(val customerName: String)
@EventTypedata class MbChildrenFullLineItemAdded( val itemId: String, val productName: String, val initialQuantity: Int, val unitPrice: Double)
@EventTypedata class MbChildrenFullQuantityAdjusted(val itemId: String, val newQuantity: Int)
@EventTypedata class MbChildrenFullLineItemRemoved(val itemId: String)
// Read Models@ReadModel@FromEvent(MbChildrenFullOrderCreated::class)data class MbChildrenFullOrder( @SetFrom("customerName", MbChildrenFullOrderCreated::class) val customer: String = "",
@ChildrenFrom(MbChildrenFullLineItemAdded::class, key = "itemId", identifiedBy = "itemId") @ChildrenFrom(MbChildrenFullQuantityAdjusted::class, key = "itemId", identifiedBy = "itemId") @RemovedWith(MbChildrenFullLineItemRemoved::class, key = "itemId") val lines: List<MbChildrenFullOrderLine> = emptyList())
data class MbChildrenFullOrderLine( val itemId: String = "",
@SetFrom("productName", MbChildrenFullLineItemAdded::class) val product: String = "",
@SetFrom("initialQuantity", MbChildrenFullLineItemAdded::class) @SetFrom("newQuantity", MbChildrenFullQuantityAdjusted::class) val quantity: Int = 0,
@SetFrom("unitPrice", MbChildrenFullLineItemAdded::class) val unitPrice: Double = 0.0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.ChildrenFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.RemovedWith;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
import java.util.Collections;import java.util.List;
// Events@EventTyperecord MbChildrenFullOrderCreated(String customerName) {}
@EventTyperecord MbChildrenFullLineItemAdded( String itemId, String productName, int initialQuantity, double unitPrice) {}
@EventTyperecord MbChildrenFullQuantityAdjusted(String itemId, int newQuantity) {}
@EventTyperecord MbChildrenFullLineItemRemoved(String itemId) {}
// Read Models@ReadModel@FromEvent(eventType = MbChildrenFullOrderCreated.class)class MbChildrenFullOrder { @SetFrom(propertyPath = "customerName", eventType = MbChildrenFullOrderCreated.class) public String customer = "";
@ChildrenFrom(eventType = MbChildrenFullLineItemAdded.class, key = "itemId", identifiedBy = "itemId") @ChildrenFrom(eventType = MbChildrenFullQuantityAdjusted.class, key = "itemId", identifiedBy = "itemId") @RemovedWith(eventType = MbChildrenFullLineItemRemoved.class, key = "itemId") public List<MbChildrenFullOrderLine> lines = Collections.emptyList();}
class MbChildrenFullOrderLine { public String itemId = "";
@SetFrom(propertyPath = "productName", eventType = MbChildrenFullLineItemAdded.class) public String product = "";
@SetFrom(propertyPath = "initialQuantity", eventType = MbChildrenFullLineItemAdded.class) @SetFrom(propertyPath = "newQuantity", eventType = MbChildrenFullQuantityAdjusted.class) public int quantity = 0;
@SetFrom(propertyPath = "unitPrice", eventType = MbChildrenFullLineItemAdded.class) public double unitPrice = 0.0;}defmodule MyApp.Events.MbChildrenOrderCreated do use Cratis.Chronicle.Events.EventType, id: "mb-children-order-created"
defstruct [:customer_name]end
defmodule MyApp.Events.MbChildrenLineItemAddedFullExample do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-added-full-example"
defstruct [:order_line_id, :product_name, :quantity]end
defmodule MyApp.Events.MbChildrenQuantityAdjusted do use Cratis.Chronicle.Events.EventType, id: "mb-children-quantity-adjusted"
defstruct [:order_line_id, :quantity]end
defmodule MyApp.Events.MbChildrenLineItemRemovedFullExample do use Cratis.Chronicle.Events.EventType, id: "mb-children-line-item-removed-full-example"
defstruct [:order_line_id]end
defmodule MyApp.ReadModels.MbChildrenOrderLine do defstruct order_line_id: nil, product_name: nil, quantity: 0end
defmodule MyApp.ReadModels.MbChildrenFullOrder do use Cratis.Chronicle.ReadModels.ReadModel, types: [lines: {:list, MyApp.ReadModels.MbChildrenOrderLine}]
defstruct order_id: nil, customer_name: nil, lines: []
from MyApp.Events.MbChildrenOrderCreated, set: [order_id: :event_source_id, customer_name: :customer_name]
children :lines, identified_by: :order_line_id do from MyApp.Events.MbChildrenLineItemAddedFullExample, key: :order_line_id, set: [order_line_id: :order_line_id, product_name: :product_name, quantity: :quantity]
from MyApp.Events.MbChildrenQuantityAdjusted, key: :order_line_id, set: [quantity: :quantity]
removed_with MyApp.Events.MbChildrenLineItemRemovedFullExample, key: :order_line_id endendimport { childrenFrom, eventType, Guid, removedWith, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
// Events@eventType()export class MbChildrenFullOrderCreated { customerName = '';}
@eventType()export class MbChildrenFullLineItemAdded { itemId: Guid = Guid.empty; productName = ''; initialQuantity = 0; unitPrice = 0;}
@eventType()export class MbChildrenFullQuantityAdjusted { itemId: Guid = Guid.empty; newQuantity = 0;}
@eventType()export class MbChildrenFullLineItemRemoved { itemId: Guid = Guid.empty;}
// Read Modelsexport class MbChildrenFullOrderLine { id: Guid = Guid.empty;
@setFrom(MbChildrenFullLineItemAdded, 'productName') product = '';
@setFrom(MbChildrenFullLineItemAdded, 'initialQuantity') @setFrom(MbChildrenFullQuantityAdjusted, 'newQuantity') quantity = 0;
@setFrom(MbChildrenFullLineItemAdded, 'unitPrice') unitPrice = 0;}
export class MbChildrenFullOrder { id: Guid = Guid.empty;
@setFrom(MbChildrenFullOrderCreated, 'customerName') customer = '';
@childrenFrom(MbChildrenFullLineItemAdded, 'itemId') @removedWith(MbChildrenFullLineItemRemoved, 'itemId') @field(Array, { genericArguments: [MbChildrenFullOrderLine] }) lines: MbChildrenFullOrderLine[] = [];}Event Processing Flow
Section titled “Event Processing Flow”The order-created event sets the parent’s customer name. Adding a line sets its product, initial quantity, and unit price. A quantity-adjustment event replaces only the matching line’s quantity; the removal event deletes that line while leaving the order intact.
Nested Children
Section titled “Nested Children”Declare another ChildrenFrom collection on a child type to build a hierarchy. Here, an organization contains departments, and each department contains teams. The team-add event’s DepartmentId selects the department that owns the team:
// Events[EventType]public record MbChildrenNestedOrganizationCreated(string Name);
[EventType]public record MbChildrenNestedDepartmentAdded(Guid Id, string Name);
[EventType]public record MbChildrenNestedDepartmentRenamed(Guid Id, string NewName);
[EventType]public record MbChildrenNestedTeamAdded(Guid Id, Guid DepartmentId, string Name);
[EventType]public record MbChildrenNestedTeamRenamed(Guid Id, string NewName);
// Read Models - all attributes work at every nesting levelpublic record MbChildrenNestedOrganization( [Key] Guid Id,
[SetFrom<MbChildrenNestedOrganizationCreated>] string Name,
[ChildrenFrom<MbChildrenNestedDepartmentAdded>( key: nameof(MbChildrenNestedDepartmentAdded.Id), identifiedBy: nameof(MbChildrenNestedDepartment.Id))] IEnumerable<MbChildrenNestedDepartment> Departments);
public record MbChildrenNestedDepartment( [Key] Guid Id,
[SetFrom<MbChildrenNestedDepartmentAdded>] [Join<MbChildrenNestedDepartmentRenamed>(eventPropertyName: nameof(MbChildrenNestedDepartmentRenamed.NewName))] // Joins work on children string Name,
[ChildrenFrom<MbChildrenNestedTeamAdded>( key: nameof(MbChildrenNestedTeamAdded.Id), identifiedBy: nameof(MbChildrenNestedTeam.Id), parentKey: nameof(MbChildrenNestedTeamAdded.DepartmentId))] // Nested children IEnumerable<MbChildrenNestedTeam> Teams);
public record MbChildrenNestedTeam( [Key] Guid Id,
[SetFrom<MbChildrenNestedTeamAdded>] [Join<MbChildrenNestedTeamRenamed>(eventPropertyName: nameof(MbChildrenNestedTeamRenamed.NewName))] // Joins work on nested children too string Name);Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.MbChildrenSectionAdded do use Cratis.Chronicle.Events.EventType, id: "mb-children-section-added"
defstruct [:section_id, :section_name]end
defmodule MyApp.Events.MbChildrenTaskAddedToSection do use Cratis.Chronicle.Events.EventType, id: "mb-children-task-added-to-section"
defstruct [:section_id, :task_id, :task_name]end
defmodule MyApp.Events.MbChildrenTaskCompleted do use Cratis.Chronicle.Events.EventType, id: "mb-children-task-completed"
defstruct [:task_id]end
defmodule MyApp.ReadModels.MbChildrenTask do defstruct task_id: nil, task_name: nil, completed: falseend
defmodule MyApp.ReadModels.MbChildrenSection do defstruct section_id: nil, section_name: nil, tasks: []end
defmodule MyApp.ReadModels.MbChildrenBoard do use Cratis.Chronicle.ReadModels.ReadModel, types: [ sections: {:list, MyApp.ReadModels.MbChildrenSection}, tasks: {:list, MyApp.ReadModels.MbChildrenTask} ]
defstruct board_id: nil, sections: []
children :sections, identified_by: :section_id do from MyApp.Events.MbChildrenSectionAdded, key: :section_id, set: [section_id: :section_id, section_name: :section_name]
children :tasks, identified_by: :task_id do from MyApp.Events.MbChildrenTaskAddedToSection, key: :task_id, parent_key: :section_id, set: [task_id: :task_id, task_name: :task_name]
from MyApp.Events.MbChildrenTaskCompleted, key: :task_id, set: [completed: true] end endendimport { childrenFrom, eventType, Guid, join, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
// Events@eventType()export class MbChildrenNestedOrganizationCreated { name = '';}
@eventType()export class MbChildrenNestedDepartmentAdded { id: Guid = Guid.empty; name = '';}
@eventType()export class MbChildrenNestedDepartmentRenamed { id: Guid = Guid.empty; newName = '';}
@eventType()export class MbChildrenNestedTeamAdded { id: Guid = Guid.empty; departmentId: Guid = Guid.empty; name = '';}
@eventType()export class MbChildrenNestedTeamRenamed { id: Guid = Guid.empty; newName = '';}
// Read Models - all decorators work at every nesting levelexport class MbChildrenNestedTeam { id: Guid = Guid.empty;
@setFrom(MbChildrenNestedTeamAdded, 'name') @join(MbChildrenNestedTeamRenamed, undefined, 'newName') // Joins work on nested children too name = '';}
export class MbChildrenNestedDepartment { id: Guid = Guid.empty;
@setFrom(MbChildrenNestedDepartmentAdded, 'name') @join(MbChildrenNestedDepartmentRenamed, undefined, 'newName') // Joins work on children name = '';
@childrenFrom(MbChildrenNestedTeamAdded, 'id', 'id', 'departmentId') // Nested children @field(Array, { genericArguments: [MbChildrenNestedTeam] }) teams: MbChildrenNestedTeam[] = [];}
export class MbChildrenNestedOrganization { id: Guid = Guid.empty;
@setFrom(MbChildrenNestedOrganizationCreated, 'name') name = '';
@childrenFrom(MbChildrenNestedDepartmentAdded, 'id', 'id') @field(Array, { genericArguments: [MbChildrenNestedDepartment] }) departments: MbChildrenNestedDepartment[] = [];}What Works Recursively
Section titled “What Works Recursively”The following .NET mapping attributes can be declared on child types, including nested children:
| Attribute | Works on Children |
|---|---|
SetFrom |
✓ |
AddFrom / SubtractFrom |
✓ |
SetFromContext |
✓ |
Join |
✓ |
Increment / Decrement / Count |
✓ |
ChildrenFrom (nested children) |
✓ |
RemovedWith / RemovedWithJoin |
✓ |
FromEvent (class-level) |
✓ |
Keep each level’s identity and parent routing explicit enough to follow. An update must reach the right parent collection as well as select the right child.
Ordering New Children
Section titled “Ordering New Children”New children are appended by default. Set Prepend = true on ChildrenFrom to insert new children first, or name a child property with OrderBy or OrderByDescending to keep the collection sorted by it. In the next example the newest comment comes first, and tasks stay sorted with the highest priority first:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;
[EventType]public record CommentPostedForOrdering(Guid CommentId, string Text);
[EventType]public record TaskAddedForOrdering(Guid TaskId, string Title, int Priority);
public record OrderedComment([Key] Guid CommentId, string Text);
public record OrderedTask([Key] Guid TaskId, string Title, int Priority);
public record OrderedBoard( [Key] Guid Id,
[ChildrenFrom<CommentPostedForOrdering>(key: nameof(CommentPostedForOrdering.CommentId), Prepend = true)] IEnumerable<OrderedComment> Comments,
[ChildrenFrom<TaskAddedForOrdering>(key: nameof(TaskAddedForOrdering.TaskId), OrderByDescending = nameof(OrderedTask.Priority))] IEnumerable<OrderedTask> Tasks);defmodule MyApp.Events.MbOrderingCommentPosted do use Cratis.Chronicle.Events.EventType, id: "mb-ordering-comment-posted"
defstruct comment_id: "", text: ""end
defmodule MyApp.Events.MbOrderingTaskAdded do use Cratis.Chronicle.Events.EventType, id: "mb-ordering-task-added"
defstruct task_id: "", title: "", priority: 0end
defmodule MyApp.ReadModels.MbOrderingComment do defstruct comment_id: "", text: ""end
defmodule MyApp.ReadModels.MbOrderingTask do defstruct task_id: "", title: "", priority: 0end
defmodule MyApp.ReadModels.MbOrderingBoard do use Cratis.Chronicle.ReadModels.ReadModel, types: [ comments: {:list, MyApp.ReadModels.MbOrderingComment}, tasks: {:list, MyApp.ReadModels.MbOrderingTask} ]
alias MyApp.Events.{MbOrderingCommentPosted, MbOrderingTaskAdded}
defstruct comments: [], tasks: []
children :comments, from: MbOrderingCommentPosted, identified_by: :comment_id, key: :comment_id, prepend: true
children :tasks, from: MbOrderingTaskAdded, identified_by: :task_id, key: :task_id, order_by: [desc: :priority]endimport { childrenFrom, eventType, Guid } from '@cratis/chronicle';
@eventType()class CommentPostedForOrdering { commentId: Guid = Guid.empty; text = '';}
@eventType()class TaskAddedForOrdering { taskId: Guid = Guid.empty; title = ''; priority = 0;}
class OrderedComment { commentId: Guid = Guid.empty; text = '';}
class OrderedTask { taskId: Guid = Guid.empty; title = ''; priority = 0;}
class OrderedBoard { id: Guid = Guid.empty;
@childrenFrom(CommentPostedForOrdering, { childType: OrderedComment, key: 'commentId', identifiedBy: 'commentId', prepend: true }) comments: OrderedComment[] = [];
@childrenFrom(TaskAddedForOrdering, { childType: OrderedTask, key: 'taskId', identifiedBy: 'taskId', orderByDescending: 'priority' }) tasks: OrderedTask[] = [];}Ordering belongs to the collection, so it covers children added by every event. When a collection has several ChildrenFrom attributes, declare the ordering on one of them or the same ordering on each; different orderings, or a sort property the child does not have, fail when the projection is built. Ordering only places new children - updating a child never moves it. See ordering new children for the full behavior.
Collections with no children
Section titled “Collections with no children”Before any child is stored, the collection field is absent rather than []. Root writes leave child collection paths untouched so they cannot erase children already added.
When Chronicle’s .NET reader materializes the model, a non-nullable collection becomes empty; a nullable collection stays null. Other readers can behave differently. Empty child collections explains which readers apply this rule and why initial values cannot seed the collection.
Best Practices
Section titled “Best Practices”Start by checking the child identity and parent routing for every event that changes the collection, not just the add event. Mark the child’s identity with [Key] or supply identifiedBy, and use an explicit parentKey where inference would be ambiguous.
If a related event should update a child without adding another item, continue with joins. For a quantity that rises and falls within each child, see counters.