Skip to content

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.

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);

View C# snippet source on GitHub

The child’s [Key] member stores that identity. The .NET client discovers it, so this example does not need an explicit identifiedBy.

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.

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);

View C# snippet source on GitHub

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.

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.Price

View C# snippet source on GitHub

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);

View C# snippet source on GitHub

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 attributes
public 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);

View C# snippet source on GitHub

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.

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);

View C# snippet source on GitHub

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.

Use RemovedWith to remove a selected child without deleting its parent. Declare it either on the collection or on the child type:

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);

View C# snippet source on GitHub

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);

View C# snippet source on GitHub

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);

View C# snippet source on GitHub

For removal keys and deleting whole read model instances, see Removal.

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 Models
public 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);

View C# snippet source on GitHub

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.

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 level
public 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);

View C# snippet source on GitHub

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.

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:

Order children
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);

View C# snippet source on GitHub

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.

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.

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.